2012-11-25 61 views
1

可以說我想要有一個Stream的正方形。一個簡單的方法來聲明這將是:爲什麼Scala編譯器不能推斷Stream類型的操作?

scala> def squares(n: Int): Stream[Int] = n * n #:: squares(n + 1) 

但這樣做,會產生錯誤:

<console>:8: error: overloaded method value * with alternatives: 
    (x: Double)Double <and> 
    (x: Float)Float <and> 
    (x: Long)Long <and> 
    (x: Int)Int <and> 
    (x: Char)Int <and> 
    (x: Short)Int <and> 
    (x: Byte)Int 
cannot be applied to (scala.collection.immutable.Stream[Int]) 
     def squares(n: Int): Stream[Int] = n * n #:: squares(n + 1) 
              ^

那麼,爲什麼不能斯卡拉推斷這顯然是一個Intn類型?有人可以解釋發生了什麼事嗎?

回答

11

這只是一個優先問題。你的表達被解釋爲n * (n #:: squares(n + 1)),這顯然不是很好的類型(因此錯誤)。

您需要添加括號:

def squares(n: Int): Stream[Int] = (n * n) #:: squares(n + 1) 

順便說一句,這不是一個推斷問題,因爲類型是已知的(即n被稱爲是Int型的,所以它不需要被推斷)。

相關問題