我试图弄清楚这个问题,并尝试了我在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);
Run Code Online (Sandbox Code Playgroud)
我的错误是:
Driver.scala:35: error: type mismatch;
found : Unit
required: scala.collection.mutable.ArrayBuffer[String]
ho = stringParse(str, 0, ho, 0);
^one error found
Run Code Online (Sandbox Code Playgroud)
当我在方法声明中的参数后面添加一个等号时,如下所示:
def stringParse ( exp: String, pos: Int, expreshHolder: ArrayBuffer[String], follow: Int ) ={....}
Run Code Online (Sandbox Code Playgroud)
它将其更改为"任何".我很困惑这是如何工作的.有任何想法吗?非常感激.
以下是关于如何解决此类问题的更一般性答案:
有时您会编写一个函数并在脑海中假设它返回类型X,但在某个地方,编译器不同意.这几乎总是在刚刚编写函数时发生,因此虽然编译器没有给你实际的源代码(它指向调用函数的行),但通常知道函数的返回类型是问题所在.
如果您没有立即看到类型问题,可以通过简单的方法明确键入您的函数.例如,如果您认为您的函数应该已经返回Int,但不知何故编译器说它找到了Unit,那么它会有助于添加: Int到您的函数中.这样,您可以帮助编译器帮助您,因为它会发现确切的位置,函数中的路径返回非Int值,这是您首先要查找的实际问题.
如果要返回值,则必须添加等号.现在,函数返回值为Any的原因是你有2个控制路径,每个控制路径返回一个不同类型的值 - 1表示满足if条件(返回值为temp),另一个是when如果条件不是(并且返回值将是b = b + 1,或者在增加之后为b).
| 归档时间: |
|
| 查看次数: |
3806 次 |
| 最近记录: |