Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

dictionary - Is Scala mapValues lazy?

When I call

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()

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...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...