簡體   English   中英

為什么我的 Scala function 返回類型 Unit 而不是最后一行?

[英]Why is my Scala function returning type Unit and not whatever is the last line?

我試圖弄清楚這個問題,並嘗試了我在 Scala 上閱讀過的不同的 styles,但它們都不起作用。 我的代碼是:

....

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

當我在方法聲明中的 arguments 之后添加一個等號時,如下所示:

def stringParse ( exp: String, pos: Int, expreshHolder: ArrayBuffer[String], follow: Int )  ={....}

它將其更改為“任何”。 我對這是如何工作的感到困惑。 有任何想法嗎? 非常感激。

這是關於如何解決此類問題的更一般的答案:

有時您會寫一個 function 並且在您的腦海中假設它返回類型X ,但編譯器在某個地方不同意。 這幾乎總是在剛剛編寫 function 時發生,因此雖然編譯器沒有為您提供實際源代碼(它指向調用 function 的行),但您通常知道函數的返回類型是問題所在。

如果您沒有立即看到類型問題,可以使用一個簡單的技巧來顯式鍵入您的 function。例如,如果您認為您的 function 應該返回Int ,但不知何故編譯器說它找到了一個Unit ,它有助於添加: Int到你的 function。這樣,你幫助編譯器幫助你,因為它會發現確切的位置,你的 function 中的路徑返回一個非Int值,這是你首先要尋找的實際問題.

如果要返回值,則必須添加等號。 現在,你的函數的返回值是 Any 的原因是你有 2 個控制路徑,每個返回一個不同類型的值 - 1 是當 if 的條件滿足時(並且返回值將是臨時的),另一個是當如果條件不是(並且返回值將是 b=b+1,或者遞增后的 b)。

class Test(condition: Boolean) {

  def mixed = condition match {
    case true  => "Hi"
    case false => 100
  }

  def same = condition match {
    case true  => List(1,2,3)
    case false => List(4,5,6)
  }

  case class Foo(x: Int)
  case class Bar(x: Int)

  def parent = condition match {
    case true  => Foo(1)
    case false => Bar(1)
  }
}
val test = new Test(true)

test.mixed   // type: Any
test.same    // type List[Int]
test.parent  // type is Product, the case class super type

編譯器將根據從條件(匹配、if/else、折疊等)返回的可能結果類型集,盡最大努力應用它可以應用的最具體的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM