简体   繁体   English

为什么“窗口化”的结果不同?

[英]why is the result of “windowed” different?

Code with List:带列表的代码:

println(listOf(1, 2, 3).windowed(1))
println(listOf(1, 2, 3).windowed(1) { it })
println(listOf(1, 2, 3).windowed(1) { it.toList() })

Result:结果:

[[1], [2], [3]]
[[3], [3], [3]]  //why is there 3 everywhere?
[[1], [2], [3]]

Code with Sequence:带序列的代码:

println(sequenceOf(1, 2, 3).windowed(1).toList())
println(sequenceOf(1, 2, 3).windowed(1) { it }.toList())
println(sequenceOf(1, 2, 3).windowed(1) { it.toList() }.toList())

Result:结果:

[[1], [2], [3]]
[[], [], []]     //why?!
[[1], [2], [3]]

Please explain请解释

It is in the documentation for the function:它在函数的文档中:

Note that the list passed to the transform function is ephemeral and is valid only inside that function.请注意,传递给转换函数的列表是短暂的,仅在该函数内部有效。 You should not store it or allow it to escape in some way, unless you made a snapshot of it.你不应该存储它或让它以某种方式逃脱,除非你制作了它的快照。

As an implementation detail, this higher order function is reusing the same list instance for each element of the window and clearing/refilling it in between.作为一个实现细节,这个高阶函数为窗口的每个元素重用相同的列表实例,并在两者之间清除/重新填充它。 This avoids having to allocate many lists.这避免了必须分配许多列表。

By passing it as the return value of the transform function, you are allowing the list instance to escape, as they warn you not to do.通过将其作为转换函数的返回值传递,您允许列表实例转义,因为它们警告您不要这样做。

In your third example, you are returning a copy of the list using toList() , so it works correctly.在您的第三个示例中,您使用toList()返回列表的副本,因此它可以正常工作。

When you do this with sequences, the results are different because the function internally handles lists and other iterable types differently.当您对序列执行此操作时,结果会有所不同,因为该函数在内部处理列表和其他可迭代类型的方式不同。 Perhaps the algorithm empties the reused list at the end.也许算法最后会清空重用列表。

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

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