在下面的代码:SCALA如何在没有所有值的情况下评估实例方法?
object intsets {
val t1= new NonEmpty(3, new Empty, new Empty)
//val t2 = t1 incl (4)
abstract class IntSet {
def incl(x:Int): IntSet
def contains(x:Int): Boolean
}
class Empty extends IntSet {
def contains(x: Int): Boolean = false
def incl(x: Int): IntSet = new NonEmpty(x, new Empty, new Empty)
override def toString = "."
}
class NonEmpty (elem: Int, left: IntSet, right: IntSet) extends IntSet {
def contains(x: Int):Boolean =
if (x < elem) return left.contains(x)
else if (x > elem) return right.contains(x)
else true
def incl(x:Int):IntSet =
if (x < elem) new NonEmpty(elem, left.incl(x),right)
else if (x > elem) new NonEmpty(elem, left, right.incl(x))
else this
override def toString = "{" + left + elem + right + "}"
}
}
我有点困惑的NonEmpty
方法时,我们不传递任何X值实例化这个类。例如,在第二行中,我保护了t1
(这意味着x没有值),REPL返回t1: NonEmpty = {.3.}
。我不知道编译器是否去def contains(x: Int):Boolean =
或不。看起来像它,但如何没有任何价值x?
“我对NonEmpty方法有点困惑”您的意思是“NonEmpty * class *”还是“* contains * method”? – sepp2k
我们在实例化'NonEmpty类时调用的方法。 'new NonEmpty(3,new Empty,new Empty)' 我不知道实例化是否触发了类内部的任何方法,或者不是它本身。 – shirin