我最近一直在玩Scala无限Streams,我注意到了一个奇怪的行为.这个想法是为了证明memoization与Streams声明为一个val.
有以下测试套件:
import org.scalatest.{Matchers, FunSuite}
class StreamsSuite extends FunSuite with Matchers {
test("natural numbers stream, proving memoization") {
var hitCounter = 0
lazy val Naturals: Stream[Int] = 1 #:: Naturals.map { n =>
hitCounter += 1
n + 1
}
Naturals.take(3).toIndexedSeq should be(Seq(1, 2, 3))
hitCounter should be(2)
Naturals.take(3).toIndexedSeq
hitCounter should be(2)
Naturals.take(4).toIndexedSeq
hitCounter should be(3)
}
}
Run Code Online (Sandbox Code Playgroud)
一切都完美和预期.但是,当我将Stream定义更改为以下列方式使用下划线占位符语法时:
lazy val Naturals: Stream[Int] = 1 #:: Naturals.map {
hitCounter += 1
_ + 1
}
Run Code Online (Sandbox Code Playgroud)
关于Stream内容的所有断言仍将保留,但hitCounter只会更新一次(并以值1结束). …
scala ×1