When exactly is the head of a Stream evaluated?

 ̄綄美尐妖づ 提交于 2019-12-03 12:00:53

-Xprint:typer is your friend, any time you want to understand exactly how some code is evaluated or types are inferred.

scala -Xprint:typer -e '0 #:: Stream( {println("evaluating 1"); 1} , 2, 3)'

val x$1: Int = 0;
Stream.consWrapper[Int](Stream.apply[Int]({
  println("evaluating 1");
  1
}, 2, 3)).#::(x$1)

The parameter of consWrapper is by-name. So even this works:

scala> (1 #:: (sys.error("!!"): Stream[Int])).head
res1: Int = 1

The head is evaluated in the moment the Stream is created.

But in you second example you don't pass a Streem as the second argument to #:: you pass a by name parameter, i.e. the complete expression Stream( {println("evaluating 1"); 1} , 2, 3) isn't evaluated at all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!