why are there different results in two scala running environments? -
i reading section 19.3 of book "programming in scala 2nd", there snippet code , description around in page 431:
note: fc17 x86_64 scala-2.9.2
class cell[t](init: t) { private[this] var current = init def = current def set(x: t) { current = x } }
i modifyed sample in 2 different enviroments: in first one, wrote following code in file cell.scala
class class b extends class c extends b class cell[+t](init: t) { private[this] var current = init def = 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 } }
and using following command, , got nothing error:
[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]$
in second, directly wrote code under repl:
scala> class cell[+t](init: t) { | private[this] var current = init | def = 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 cast b @ .<init>(<console>:25) @ .<clinit>(<console>)
accordding uderstanding covariant , lower-bound, think second result right, not know why first 1 did not throw error?
i know must missing something, want compiling error second, should do?
you're not going compile error, because there's no problem @ compile time. classcastexception
runtime exception.
you should notice exception occurs after evaluate a1.get
, rather when perform cast in a1.set
. more precisely, occurs when try assign return value variable.
in first scenario a1.get
not assigned value. in second, you're assigning value such res0
etc.
you can show problem trying following in repl:
scala> a1.get java.lang.classcastexception: java.lang.string cannot cast b scala> println(a1.get) dillon
Comments
Post a Comment