Scala mapValues是懒惰吗?
发布时间:2020-12-16 08:50:17 所属栏目:安全 来源:网络整理
导读:我打电话的时候 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() 如
我打电话的时候
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里面有一个debug print语句,我得到这个输出: Before ...head item... After ...debug print statement from fn... ...debug print statement from fn... 我不明白为什么在打印“After”之后调用调试打印语句,我不明白为什么我得到它两次—除非mapValues创建一个懒惰的地图? 解决方法
Yes it is.它映射到一个中间类,它保存fn并且在访问之前不会进行评估(一次又一次).
def mapValues[W](f: V => W): Map[K,W] = new MappedValues(f) 如果您不想进行延迟评估,请使用严格的地图.那是: collection map { case (k,v) => (k,fn(v)) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |