0

私の関数が最終的にユニットではなく正しい型を出力することをscalaが理解するために、関数と関数の一部を配置する必要がある順序を本当に理解していません。eclipse がこれらの行で何を伝えているかについて、コメント (7 行目と最後の行) を作成しました。コンパイラへの洞察は大歓迎です。

object braces {
 def balance(chars: List[Char]): Boolean = {

    def rightBraces(chars: List[Char], openCount: Int, closeCount: Int): Boolean = {
        if (!chars.tail.isEmpty) {
            if (chars.head == '(') rightBraces(chars.tail, openCount + 1, closeCount)
            /*type mismatch;  found   : Unit  required: Boolean*/else if (chars.head == ')') rightBraces(chars.tail, openCount, closeCount + 1)
        }
        else {
            if ((chars.head == '(')&&(openCount == (closeCount - 1))) true
            else if ((chars.head == ')')&&(openCount == (closeCount + 1))) true
            else (openCount == closeCount)
        }
    }

    def wrongBrace(chars: List[Char]): Boolean = {
     if (!chars.tail.isEmpty) {
         if (chars.head == ')') false
         else if (chars.head == '(') rightBraces(chars.tail, 1, 0)
         else wrongBrace(chars.tail)
     }
     else false
    }

    wrongBrace(chars)

 }
}//Missing closing brace `}' assumed here
4

1 に答える 1

1

問題はここにあります:

    if (!chars.tail.isEmpty) {
        if (chars.head == '(') rightBraces(chars.tail, openCount + 1, closeCount)
        else if (chars.head == ')') rightBraces(chars.tail, openCount, closeCount +1)
    }

内側の if ブロックでは、if も else if も true に評価されない可能性があります。その場合、値は返されず、コンパイラはデフォルトで Unit を返します。

そのため、 else ブロック内にデフォルトのケースを指定するか、必要に応じてelse ifをelse に変更する必要があります。

于 2012-10-03T03:10:29.000 に答える