【发布时间】:2012-07-01 09:13:58
【问题描述】:
ListNode example,取自 Scalas 主页,如下所示:
case class ListNode[+T](h: T, t: ListNode[T]) {
def head: T = h
def tail: ListNode[T] = t
def prepend[U >: T](elem: U): ListNode[U] =
ListNode(elem, this)
}
通过这个类,我们可以创建如下对象:
val empty: ListNode[Null] = ListNode(null, null)
val strList: ListNode[String] = empty.prepend("hello")
.prepend("world")
val anyList: ListNode[Any] = strList.prepend(12345)
如我们所见,我们可以在String 节点前添加一个整数值。我想,这是因为类型参数U 将自动设置为Any,当给prepend 方法提供整数时(因为Int 不是String 的超类型)。
当尝试使用自己的下限示例时,我会得到一个错误:
scala> class E[T >: String]
defined class E
scala> new E[Any]
res1: E[Any] = E@135f0a
scala> new E[Int]
<console>:11: error: type arguments [Int] do not conform to class E's type param
eter bounds [T >: String]
val res2 =
^
<console>:12: error: type arguments [Int] do not conform to class E's type param
eter bounds [T >: String]
new E[Int]
^
为什么这里的Int 类型不会像ListNode 示例中那样自动被视为Any 类型?
更新 1:这也有效(没有明确说明新的 ListNode 应该是 Any 类型)
scala> val empty: ListNode[Null] = ListNode(null, null)
empty: example.listNode.ListNode[Null] = ListNode(null,null)
scala> empty.prepend("hello").prepend("world")
res0: example.listNode.ListNode[java.lang.String] = ListNode(world,ListNode(hell
o,ListNode(null,null)))
scala> val strList: ListNode[String] = empty.prepend("hello").prepend("world")
strList: example.listNode.ListNode[String] = ListNode(world,ListNode(hello,ListN
ode(null,null)))
scala> strList.prepend(12345)
res1: example.listNode.ListNode[Any] = ListNode(12345,ListNode(world,ListNode(he
llo,ListNode(null,null))))
【问题讨论】:
标签: scala type-parameter lower-bound