function - 为什么我的Scala函数返回类型Unit而不是最后一行?

标签 function scala

我试图找出问题所在,并尝试了我在Scala上阅读过的各种样式,但是它们都不起作用。我的代码是:

....

val str = "(and x y)";

def stringParse ( exp: String, pos: Int, expreshHolder: ArrayBuffer[String], follow: Int )  

    var b = pos; //position of where in the expression String I am currently in
    val temp = expreshHolder; //holder of expressions without parens
    var arrayCounter = follow; //just counts to make sure an empty spot in the array is there to put in the strings

    if(exp(b) == '(') {
        b = b + 1;

        while(exp(b) == ' '){b = b + 1} //point of this is to just skip any spaces between paren and start of expression type

        if(exp(b) == 'a') {
               temp(arrayCounter) = exp(b).toString; 
               b = b+1; 
               temp(arrayCounter)+exp(b).toString; b = b+1; 
               temp(arrayCounter) + exp(b).toString; arrayCounter+=1}
               temp;

         }

}

val hold: ArrayBuffer[String] = stringParse(str, 0, new ArrayBuffer[String], 0);
for(test <- hold) println(test);

我的错误是:
Driver.scala:35: error: type mismatch;
found   : Unit
 required: scala.collection.mutable.ArrayBuffer[String]
ho = stringParse(str, 0, ho, 0);
                ^one error found

当我在方法声明中的参数之后添加等号时,如下所示:
def stringParse ( exp: String, pos: Int, expreshHolder: ArrayBuffer[String], follow: Int )  ={....}

它将其更改为“任何”。我对这是如何工作感到困惑。有任何想法吗?非常感激。

最佳答案

如果要返回值,则必须添加等号。现在,函数返回值为Any的原因是,您有2条控制路径,每条返回的路径的类型不同-1是满足if条件的条件(返回值为temp),而另一条是if的条件不是(返回值将为b = b + 1或递增后的b)。

关于function - 为什么我的Scala函数返回类型Unit而不是最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10005326/

相关文章:

scala - 如何使用 Spark 函数将日期从 yyyy-mm-dd 更改为 dd-mm-yyy

scala - 为什么表达式的值取决于分配给它的变量?

list - 在 Common Lisp 的 2 个列表中递归应用函数

Javascript 函数序列示例

c++ - 如何在不解析的情况下将重载函数指针作为参数传递 (C++03)

scala - 如何使用 Spark 从 svd 分量重建原始矩阵

c - 为什么我收到段错误 : 11

c++ - 适合在函数参数中将字符串文字转换为 char * 吗?

java - Dbpedia 提取框架 - 如何去除 mediawiki 格式标记

scala - 在 Scala 中使用稳定标识符的后果是什么?