【发布时间】:2017-05-26 07:23:59
【问题描述】:
我要匹配第一个元素为 0 或 1 或 Null 的 Array,示例如下:
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 不安全
-
谢谢! @Cyäegha,我之前没有看到这个问题,实际上我的问题是一样的。
-
通常你应该返回 Option[Node] 然后使用模式匹配看看结果是什么
-
谢谢,我会修改它,还有一个问题,为什么 asInstanceOf 不安全?
-
这里有一些关于此的 cmets:stackoverflow.com/questions/6686992/… 根据我的理解,如果对象为 Null,asInstanceOf 只会抛出异常,这不是处理对象的“惯用”方式:
标签: arrays scala pattern-matching