如果 Scala 中需要不可变数组,则返回 IndexesSeq 而不是 Array 是否正确?
我的一个函数生成一个数组——一组有序、连续编号的记录。但据我所知,Scala Array 是一个可变集合,而函数式方法表明,在一般情况下返回不可变集合更有意义。因此,我只需调用 Array.toIndexedSeq 来返回 IndexedSeq 而不是 Array。这可以被认为是正确的做法吗?它是否会引入任何可能影响函数和结果使用并可能被认为是不良的不明显行为?对于这个问题有更好的做法吗?
A function of mine produces an array - an ordered, contiguously numbered set of records. But as far as I know Scala Array is a mutable collection, while functional approach suggests it would make more sense to return an immutable collection in a general case. So I just call Array.toIndexedSeq
to return an IndexedSeq
instead of Array
. Can this be considered a correct thing to do? Doesn't it introduce any inobvious behaviour which can influence the function and the result usage and be probably considered undesirable? Are there any better practices for the issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。
不,据我所知没有。
如果可能的话,尝试完全消除数组的使用,除非性能至关重要。
Yes.
No, not that I know of.
If possible, try to eliminate the use of array altogether, unless of course the performance is paramount.
我能想到的唯一可能不明显的事情是 array.toIndexedSeq 不会像 Java 的 Collections.unmodifying* 方法那样在数组本身上创建一个简单的包装器,但将元素复制到一个新集合中。 (否则数组中的后续更改可能会导致“不可变”序列突然发生突变。)
The only possibly non-obvious thing I can think of is that
array.toIndexedSeq
doesn't create a simple wrapper over the array itself like Java'sCollections.unmodifiable*
methods do, but copies the elements into a new collection. (Otherwise later changes in the array could cause the "immutable" sequence to suddenly mutate.)