Lets say I want to have a Stream of squares. A simple way to declare it would be:
scala> def squares(n: Int): Stream[Int] = n * n #:: squares(n + 1)
Run Code Online (Sandbox Code Playgroud)
But doing so, yields an error:
<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)
^
Run Code Online (Sandbox Code Playgroud)
so, why can't Scala infer the type of n which is obviously an Int? Can someone please explain what's going on?
Gia*_*ian 11
这只是一个优先问题.你的表达式被解释为n * (n #:: squares(n + 1)),这显然不是很好的类型(因此错误).
您需要添加括号:
def squares(n: Int): Stream[Int] = (n * n) #:: squares(n + 1)
Run Code Online (Sandbox Code Playgroud)
顺便说一下,这不是一个推理问题,因为类型是已知的(即,n被称为是类型的Int,所以它不需要被推断).