正确的功能定义结构?

时间:2012-10-02 23:57:31

标签: scala

我真的不明白函数和函数部分需要布局的顺序,以便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

1 个答案:

答案 0 :(得分: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 if或else if not evalu to true。在这种情况下,不返回任何值,编译器默认返回一个单元。

因此,您必须在 else块中提供默认案例,或者将其他更改为其他,如果合适的话。