java - 为什么类型参数绑定(bind) T < : Comparable[T] fail for T = Int?

标签 java scala scala-2.8

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/

相关文章:

java - 如何使用 getter 函数访问另一个类中的私有(private)变量?

Scala - 返回类型参数化对象的类型参数化特征方法 - 如何实现?

scala - 运行 Scala MongoDB 连接器时出现 java.lang.ClassNotFoundException : org. apache.spark.sql.DataFrame 错误

scala - 如何编写一个返回与传递给它的集合类型相同的集合类型的 zipWith 方法?

scala - 双变量参数列表

java - Apple 最近的 Java 更新删除了 Java 首选项,如何从 shell 更改?

Java - 拖动绘制的对象

java - .class 我的程序的预期错误

forms - Play Framework - 使用表单助手时如何更改输入的标签?

scala - 在其他长期运行的 Actor 在场的情况下,如何防止 Actor 饥饿?