方法调用中的选项不编译

时间:2014-12-04 18:57:32

标签: scala

为了获得二叉树的高度,我使用以下代码:

object optionfun {
  println("Welcome to the Scala worksheet")

  case class Node(var isVisited: Boolean, var leftNode: Option[Node], var rightNode: Option[Node], name: String) {
    def this(name: String) = this(false, None, None, name)
  }

  val a = new Node("a")
  val b = new Node("b")
  val c = new Node("c")
  a.leftNode = Some(b)
  a.rightNode = Some(c)

  def getHeight(root: Option[Node]): Int = {

    //if root contains a None type then it should return 0, should I pattern match on the option type here?
    Math.max(getHeight(root.leftNode),
      getHeight(root.rightNode.get)) + 1
  }

    getHeight(a)
}

但我收到了行的编译错误:

Math.max(getHeight(root.leftNode)

错误是:

Multiple markers at this line - value leftNode is not a member of Option[optionfun.Node] - value 
 leftNode is not a member of Option[Node]

我以某种方式混淆了这些类型,但我不知道传入getHeight方法的内容“root.leftNode”是否为Option类型?

1 个答案:

答案 0 :(得分:0)

接受root作为Option[Node]的问题在于,您不能只调用root.leftNode,必须mapmatch Option 1}}。

你可以在没有Option的情况下重写它:

def getHeight(root: Node): Int = {
    Math.max(
        root.leftNode.map(getHeight(_)).getOrElse(0),
        root.rightNode.map(getHeight(_)).getOrElse(0)
    ) + 1
}

Option

def getHeight(root: Option[Node]): Int = root match {
   case Some(r) => Math.max(getHeight(r.leftNode), getHeight(r.rightNode)) + 1
   case None => 0
}