为什么对于T = Int,绑定到T的类型参数T <:Comparable [T]失败? [英] Why does the type parameter bound T &lt;: Comparable[T] fail for T = Int?

查看:59
本文介绍了为什么对于T = Int,绑定到T的类型参数T <:Comparable [T]失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

我将如何定义Foo,以便可以使用Int参数化它,但仍然能够使用其实例变量执行某些排序行为?

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?

推荐答案

使用视图绑定.

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

这篇关于为什么对于T = Int,绑定到T的类型参数T <:Comparable [T]失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆