Scala mapValues是否懒惰? [英] Is Scala mapValues lazy?

查看:193
本文介绍了Scala mapValues是否懒惰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用

System.err.println("Before")
System.err.flush()
val foo: Map[Int, T] = t mapValues (fn(_))
System.err.println(foo.head) //prevent optimiser from delaying the construction of 'foo' 
System.err.println("After")
System.err.flush()

fn 里面有一个调试打印声明,我得到这个输出:

with fn having a debug print statement inside, I get this output:

Before
...head item...
After
...debug print statement from fn...
...debug print statement from fn...

我不明白为什么在打印After之后调用打印语句,我不明白为什么我会得到它两次 - 除非 mapValues 创建一个懒惰的地图?

I don't understand why the debug print statements are being called after "After" is printed, and I don't understand why I'm getting it twice --- unless mapValues creates a lazy map?

推荐答案

是它是。它映射到一个中间类,保存 fn ,直到访问(一次又一次)才进行评估。

Yes it is. It maps to an intermediate class that holds fn and doesn't evaluate until access (again and again).

def mapValues[W](f: V => W): Map[K, W] = new MappedValues(f)

如果您不想懒惰评估,请使用严格的地图。那就是:

Use a strict map if you don't want lazy evaluation. That is:

collection map { case (k, v) => (k, fn(v)) }

这篇关于Scala mapValues是否懒惰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆