简体   繁体   English

Scala流评估

[英]Scala streams evaluation

Suppose I have this code 假设我有这段代码

val stream = Stream.continually(1)
val s = stream.take(10).map(i => {
  throw new RuntimeException
  i
})

As far as I understand, the function passed to map is evaluated when the corresponding element in stream s is accessed. 据我了解,当访问流s中的相应元素时,将评估传递给map的函数。 If s is never iterated and no element is ever accessed, why does the exception get thrown? 如果从未迭代s并且从未访问过任何元素,为什么会引发异常?

The first element of the Stream is always evaluated. Stream的第一个元素始终被评估。

This will always throw. 这将总是抛出。

val stream = Stream.iterate(0)(_ + 1)
val s = stream.take(10).map(i => {
  if (i == 0) throw new RuntimeException
  i
})

But this will not until s(1) is referenced. 但这要等到引用了s(1)

val stream = Stream.iterate(0)(_ + 1)
val s = stream.take(10).map(i => {
  if (i > 0) throw new RuntimeException
  i
})

It is evaluated the first time, 第一次评估,

scala> val stream = Stream.continually(1)
stream: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> val newStream = stream.take(10).zipWithIndex.map{case (value, index) => { println(s"processing ${index}"); value * 2 } }
processing 0
newStream: scala.collection.immutable.Stream[Int] = Stream(2, ?)

So, throws exception in your case, because its evaluating first time 因此,在您的情况下引发异常,因为它是第一次评估

scala> val newStream = stream.take(10).zipWithIndex.map{case (value, index) => { println(s"processing ${index}"); throw new Exception; value * 2 } }
processing 0
java.lang.Exception
  at .$anonfun$newStream$1(<console>:12)
  at .$anonfun$newStream$1$adapted(<console>:12)
  at scala.collection.immutable.Stream.map(Stream.scala:415)
  ... 29 elided

You can verify by adding a check only if not the first time as below 您可以仅通过以下方式添加支票进行验证:

scala> val newStream = stream.take(10).zipWithIndex.map{case (value, index) => { println(s"processing ${index}"); if(index > 0 ) throw new Exception; value * 2 } }
processing 0
newStream: scala.collection.immutable.Stream[Int] = Stream(2, ?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM