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) ^
第二个表达式是类型擦除的结果吗?
我将如何定义Foo,以便可以使用Int参数化它,但仍然能够对其实例变量执行一些排序行为?
使用视图绑定。
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