【问题标题】:Why can Scala compiler not infer Stream type operations?为什么 Scala 编译器不能推断 Stream 类型的操作?
【发布时间】:2012-11-25 16:34:15
【问题描述】:

假设我想要一个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 的类型,这显然是 Int?有人可以解释一下发生了什么吗?

【问题讨论】:

    标签: scala stream


    【解决方案1】:

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

    需要加括号:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多