为什么 "windowed" 的结果不同?

why is the result of "windowed" different?

带有列表的代码:

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

结果:

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

序列代码:

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

结果:

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

请说明

它在函数的文档中:

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.

作为一个实现细节,这个高阶函数正在为 window 和 clearing/refilling 之间的每个元素重用相同的列表实例。这避免了必须分配许多列表。

通过将其作为转换函数的 return 值传递,您允许列表实例转义,因为他们警告您不要这样做。

在您的第三个示例中,您正在使用 toList() return 复制列表,因此它可以正常工作。

当您对序列执行此操作时,结果会有所不同,因为该函数在内部以不同方式处理列表和其他可迭代类型。也许算法在最后清空了重用列表。