SCALA如何在没有所有值的情况下评估实例方法?

时间:2017-07-17 18:56:27

标签: 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 + "}"
  }

}

当我们实例化此类而不传递任何x值时,我对NonEmpty方法有点困惑。例如,在第二行中,我保护t1(这意味着没有x的值),REPL返回t1: NonEmpty = {.3.}

我无法弄清楚编译器是否转到def contains(x: Int):Boolean =。看起来确实如此,但是怎么没有x的任何价值?

1 个答案:

答案 0 :(得分:1)

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

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

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

val t1 = new NonEmpty(3, new Empty, new Empty)
t1.contains(1) // should return false
t1.contains(3) // should return true
相关问题