Scala Type Parameter "Gotcha"
November 25th, 2009
During the exercises for my Scala tutorial at QCon last week, one of the students was mystified by the error message he got when he ran the following (greatly simplified…) script:
trait Doubler[T] {
def double(t: T): T
}
class IntDoubler[Int] extends Doubler[Int] {
def double(t: Int) = t * 2
}
(fragment of ....scala):5: error: value * is not a member of Int
def double(t: Int) = t * 2
^
one error found
What?! Of course Int has the * member method!!
Well, yes, the final class scala.Int type does have a * method, but that’s not what the word Int means in the declaration of IntDoubler. Because he wrote IntDouble[Int] instead of IntDouble (without a type parameter), he effectively said that IntDouble is still parameterized and the type parameter now has the name Int. The declaration that yields the intended behavior is this:
class IntDoubler extends Doubler[Int] {
def double(t: Int) = t * 2
}
This is a common beginner (and not-so-beginner) mistake. We discussed it in Programming Scala and I posted an enhancement request today for the Scala compiler to provide some “help”. The compiler could disallow any type name that is in scope to be used as a type parameter name, as in our example, or the compiler could at least warn you that you probably didn’t mean for the new type to have a type parameter.




Sorry, comments are closed for this article.