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 参数化它,但仍然能够用它的实例变量执行一些排序行为?
最佳答案
使用 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
关于java - 为什么类型参数绑定(bind) T < : Comparable[T] fail for T = Int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4113357/