You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala不可变集合的不可变性:++操作是否会创建新对象?

Does Scala's ++ Create a New Object Here?

Great question—let's break this down clearly.

1. Yes, the ++ operation does create a new object

Looking at your code:

object Dcoder extends App { 
  var array = Array("abc","xyz") 
  var change = array ++ Array("change of object") 
}

The ++ operator concatenates the two arrays: it takes all elements from array and the new Array("change of object"), then creates a brand new array instance containing all these elements. The original array variable still points to the original two-element array—its contents and length haven't changed at all. You can verify this by checking array.length (still 2) and change.length (now 3) after the operation.

2. A key clarification about immutable vs mutable collections

Wait a second—Scala's Array is actually a mutable collection (you can modify its elements in place, e.g., array(0) = "def"). So your initial assumption about using an immutable collection here isn't quite right.

That said, even for mutable collections, operations like ++ (which produce a modified version of the collection) almost always return a new instance instead of altering the original.

If you were using a true immutable collection (like scala.collection.immutable.List or scala.collection.immutable.ArraySeq), then any operation that changes the length (or any element, since immutable collections can't be modified after creation) would necessarily create a new object. That's a defining trait of immutable collections—they can't be changed, so any "update" results in a new instance.

In your specific code, the new object is created because the ++ operation for Array is designed to return a concatenated copy, not because Array is immutable. But if you swapped Array for an immutable collection type, the length change would be the direct cause of the new object creation, as that's how immutable collections work.

内容的提问来源于stack exchange,提问作者user9715375

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:05:32