1

可以说我想要一个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)
                                            ^

那么,为什么 Scala 不能推断出n显然是 a的类型Int?有人可以解释发生了什么吗?

4

1 回答 1

11

这只是一个优先级问题。您的表达式被解释为n * (n #:: squares(n + 1)),这显然不是很好的类型(因此出现错误)。

您需要添加括号:

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

顺便说一句,这不是推理问题,因为类型是已知的(即,n已知是 type Int,因此不需要推理)。

于 2012-11-25T16:37:47.440 回答