0
我想匹配一个数组,其第一个元素是0或1或Null,下面是例如:Scala的占位符阵列,用于图案匹配
def getTheta(tree: Node, coding: Array[Int]): Array[Double] = {
val theta = coding.take(coding.length - 1) match {
case Array() => tree.theta
case Array(0,_) => getTheta(tree.right.asInstanceOf[Node],coding.tail)
case Array(1,_) => getTheta(tree.left.asInstanceOf[Node],coding.tail)
}
theta
}
树类定义是:
sealed trait Tree
case class Leaf(label: String, popularity: Double) extends Tree
case class Node(var theta: Array[Double], popularity: Double, left: Tree, right: Tree) extends Tree
其实我知道Array(0,__)或Array(1,_)是错误的,但我关心的只是Array的第一个元素,我该如何匹配它?
有人可以帮助我吗?
避免使用asInstanceOf不安全 – Pavel
谢谢! @ Cyeegha,之前我没有看到这个问题,实际上我的问题也是一样的。 – Yang
通常你应该返回Option [Node],然后使用模式匹配来查看结果是什么 – Pavel