scala> class Foo[T <: Comparable[T]](val x : T)
defined class Foo
scala> (3: Int).asInstanceOf[Comparable[Int]]
res60: java.lang.Comparable[Int] = 3
scala> new Foo(3)
<console>:13: error: inferred type arguments [Int] do not conform to class Foo's type parameter bounds [T <: java.lang.Comparable[T]]
new Foo(3)
^
Is the 2nd expression the result of type erasure?
How would I go about defining Foo so that I could parameterize it with Int but still be able to perform some ordering behavior with its instance variable?
Use a view bound.
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class Foo[T <% Comparable[T]](val x : T)
defined class Foo
scala> new Foo(3)
res0: Foo[Int] = Foo@9aca82
The question, as stated, is still unanswered (though "use view bounds" solves the problem, which is more useful). The answer is simply that an Int
in Scala is supposed to be equivalent to an int
in Java, which is not a class at all, and, therefore, cannot even be a Comparable
(though that could be solved in Java 7 with defender methods... I wonder if they'll do it).
The solution given, to use a view bound, is used throughout Scala to solve the problem of a class that could implement something but doesn't, because it is not under Scala's control -- ie, Java classes.
And, of course, it can be used by programmers themselves to deal with similar stuff from libraries and frameworks, or simply to produce wrappers around a library to give it a Scala-ish feeling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With