I’ve heard a bit about Scala*, but I’m still very much a complete newbie. The languages I’m most familiar with are Java (along with C#/C++/C) and Python, so I’m treating it as a sort of mixture of the two. Messing about in an interactive tutorial I got to a section treating the interpreter as a calculator. In a regular handheld calculator dividing two integers commonly results in a decimal, but in a programming language (like Scala) where those are completely different “types”, it’s likely to round the result into another integer. So to use math theory speak, integers are closed under division, their “domain” is equal to their “image”, “range” or “codomain”. I decided to try changing that (should the verb be “opening”? “unclosing”?). I noticed that the Int class has a toDouble method, and sure enough Double does as well. I hoped that ducktyping by itself would be sufficient, but unfortunately what would be a primitive in Java is merely an Any in Scala, and when I tried ducktyping it insisted they needed to be AnyRef instead (analogous to an Object in Java). Fortunately, implicit classes allow us to treat them otherwise.

implicit class SuperInt(val i:Int) extends AnyRef {      
  def toDouble = i.toDouble     
}
implicit class SuperDouble(val d:Double) extends AnyRef {      
  def toDouble = d.toDouble     
}
def divide( numerator: {def toDouble:Double },
            denominator: {def toDouble:Double }) = {  
 numerator.toDouble/denominator.toDouble    
}

The divide function works the same whether you pass in an Int or Double. Doing some googling, I found that implicitly converting Any to AnyRef is frowned upon in Scala, but I’m way too ignorant to know the reasons, having only found out they were different things from the same people doing the frowning. Those who know why, or who have suggestions for the right (what’s analogous to “Pythonic”?) way to do things are welcome to chime in.

*I don’t think Steve Yegge’s ideological ranking of languages was the first place, but it’s entertaining enough to link. And yes, annoyance with the “liberalism” of one language (JavaScript) did inspire me look up something in the opposite direction. Although I still don’t actually know what about Scala makes it more “conservative” than the C family.

About these ads