2017-07-17 35 views
0

在下面的代码: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?

+0

“我对NonEmpty方法有点困惑”您的意思是“NonEmpty * class *”还是“* contains * method”? – sepp2k

+0

我们在实例化'NonEmpty类时调用的方法。 'new NonEmpty(3,new Empty,new Empty)' 我不知道实例化是否触发了类内部的任何方法,或者不是它本身。 – shirin

回答

1

def contains(x:Int)是类中的方法。你会用一个参数(x)调用它,它会告诉你该值是否存在于该集合中。

new NonEmpty(3,new Empty,new Empty)只运行构造函数。在Scala中,构造函数由类的第一行以及任何不在def中的代码组成。

这意味着包含(x:Int)在构造对象时不会被调用。

val t1 = new NonEmpty(3, new Empty, new Empty) 
t1.contains(1) // should return false 
t1.contains(3) // should return true 
+0

所以基本上我的't1'实例只是返回非空的toString方法? – shirin

+0

是的。 t1是NonEmpty的一个实例,REPL将调用NonEmpty的toString()。这与在Scala代码中调用println(t1)相同。 – sheunis

+0

所以如果我想在我的实例上调用一个方法,我会't1.contains(1)'?甜!!谢谢。 – shirin

相关问题