我想弄清楚這個問題,並嘗試了我在Scala上閱讀過的不同樣式,但沒有一個能夠工作。我的代碼是:爲什麼我的Scala函數返回類型Unit而不是最後一行是什麼?
....
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) ={....}
它它改變「任何」。我很困惑這是如何工作的。有任何想法嗎?非常感激。
+1對於新手總是會面對的事情+1。這個解釋也有點反直覺。 – aitchnyu 2012-04-04 06:41:50