2010-06-02 55 views
4

說我有一些Scala代碼是這樣的:爲什麼我不能在for-yield表達式上調用方法?

// Outputs 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 
println(squares) 

def squares = { 
    val s = for (count <- 1 to 10) 
       yield { count * count } 
    s.mkString(", "); 
} 

爲什麼我不得不使用臨時VAL S'我嘗試這樣做:

def squares = for (count <- 1 to 10) 
        yield { count * count }.mkString(", ") 

失敗,出現此錯誤消息編譯:

error: value mkString is not a member of Int 
    def squares = for (count <- 1 to 10) yield { count * count }.mkString(", ") 

不宜mkString被稱爲由for環路返回的集合?

回答

18

有一個缺失的括號。您想針對for表達式的結果調用mkString方法。如果沒有額外的圓括號,編譯器會認爲你想調用mkString- {count * cout}這是一個Int

scala> def squares = (for (count <- 1 to 10) yield { count * count }).mkString(", ") 
squares: String 

scala> squares 
res2: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 

無論如何,我建議你應該使用map方法代替:

scala> 1 to 10 map { x => x*x } mkString(", ") 
res0: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 
+2

他的理解是,你所提供的完全一樣的地圖方法只是語法糖。在我看來,你想使用的僅僅是品味的問題。 – 2010-06-02 14:42:25

5

只要把括號周圍的for循環和它的作品:

scala> (for (count <- 1 to 10) yield { count * count }).mkString(", ") 

res0: String = 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

3

當你可以打電話mkString,就像你在你身邊ond的例子中,它沒有在集合上被調用,而是在返回的每個單獨的整數上,因此錯誤消息:mkString is not a member of Int
如果你想呼籲for..yield表達自己的方法,你需要加上括號它:

def squares = (for (count <- 1 to 10) yield { count * count }).mkString(", ")