【发布时间】:2014-04-24 12:40:17
【问题描述】:
我正在阅读“scala 2nd 编程”一书的第 19.3 节, 431页有一个sn-p代码和一些描述:
注意:FC17 x86_64 Scala-2.9.2
class Cell[T](init: T) {
private[this] var current = init
def get = current
def set(x: T) { current = x }
}
我在两个不同的环境中修改了这个示例: 在第一个中,我在文件 Cell.scala 中编写了以下代码
class A
class B extends A
class C extends B
class Cell[+T](init: T) {
private[this] var current = init
def get = current
def set[U >: T](x: U) {
current = x.asInstanceOf[T]
println("current " + current)
}
}
object Cell {
def main(args: Array[String]) {
val a1 = new Cell[B](new B)
a1.set(new B)
a1.set(new String("Dillon"))
a1.get
}
}
并使用以下命令,没有任何错误:
[abelard <at> localhost lower-bound]$ scalac Cell.scala
[abelard <at> localhost lower-bound]$ scala -cp . Cell
current B <at> 67591ba4
current Dillon
Dillon
[abelard <at> localhost lower-bound]$
第二个,我直接写了REPL下的代码:
scala> class Cell[+T](init: T) {
| private[this] var current = init
| def get = current
| def set[U >: T](x: U) {current = x.asInstanceOf[T]
| }}
defined class Cell
scala> val a1 = new Cell[B](new B)
a1: Cell[B] = Cell <at> 6717f3cb
scala> a1.set(new B)
scala> a1.set(new String("Dillon"))
scala> a1.get
java.lang.ClassCastException:
java.lang.String cannot be cast to B
at .<init>(<console>:25)
at .<clinit>(<console>)
根据我对协变和下限的理解, 我认为第二个结果是对的,但我不知道为什么 第一个没有抛出任何错误?
我知道我必须遗漏一些东西,我想要编译 第二个错误,我该怎么办?
【问题讨论】:
标签: scala