Scala - 不使用可选的map和fold时更正语法

时间:2016-11-11 11:29:40

标签: scala

在不使用Optional对象的情况下实现以下代码的正确语法是什么?

我正在进行“双重检查”,并且没有必要使用Optional,因为该对象永远不会是Nil。

case class Node(key:Int,
            children:List[Node] = Nil,
            valid:Option[Boolean] = Some(false))

def rankingChildren(node:Option[Node], score:Double = 0, depth:Int = 0):Double =
  node
    .map(_.children.filter(n => n.valid == Some(true)).fold(score)((acc, h) =>
      rankingChildren(Some(h.asInstanceOf[Node]), acc.asInstanceOf[Double] + 1)
    .getOrElse(score).asInstanceOf[Double]

我试过:

def rankingChildren(node:Node, score:Double = 0, depth:Int = 0): Double =
  node.children.filter(n => n.valid == Some(true)).fold[Double](score)((acc, h) =>
      rankingChildren(h.asInstanceOf[Node], acc.asInstanceOf[Double] + 1, depth + 1))

但是我在编译时遇到了另一个错误:

Error:(75, 60) type arguments [Double] do not conform to method fold's type parameter bounds [A1 >: models.Node]
  node.children.filter(n => n.valid == Some(true)).fold[Double](score)((acc, h) =>

如何更改它并且可以使用fold()来避免强制转换?

0 个答案:

没有答案