Scala foreach回归

时间:2012-10-17 21:38:39

标签: java scala foreach return

如何使此方法有效?

def filled(b: Board): Board = {
  b.next foreach { n =>
    if (n.filled) n
    else filled(n)
  }
}

我需要它在首次填充n(n.filled == true)之后返回,就像在Java中一样。

现在我明白了:

chess-knight.scala:72: error: type mismatch;
 found   : Unit
 required: this.Board
    b.next foreach { n =>
           ^
one error found

谢谢!

1 个答案:

答案 0 :(得分:6)

这不是你需要的吗?

def filled(b: Board): Board = b.next find {_.filled} get

假设b.nextSeq[Board]且始终至少有一个filled Board

如果你坚持纯粹的功能更喜欢利用List上的模式匹配的方法:

def filled(b: Board): Board = {
  b.next match {
    case n :: _ if(n.filled) => n
    case _ :: rest => filled(rest)
    case Nil => throw NoSuchElementException
}