https://kotlinlang.org logo
Title
b

benleggiero

08/21/2017, 3:25 AM
Why won't this compile?
class Foo(var values: MutableList<String>)

class Bar(var foo: Foo) {
    fun bar() {
        foo.values += "Baz"
    }
}
k

karelpeeters

08/21/2017, 7:29 AM
There's an ambiguity between
Collections.plus
and
MutableList.plusAssign
. The former is only applicable when the field is a
var
, so a fix would be to make it a val. I don't think you can even have a
var list: MutableList
with`+=` working.
b

benleggiero

08/21/2017, 1:17 PM
That seems like something that should be fixed...
k

karelpeeters

08/21/2017, 1:17 PM
I don't really think there's even a fix.
b

benleggiero

08/21/2017, 3:31 PM
Swift addresses this by having just one
struct
for both mutable and immutable versions, and then marking specific functions as
mutating
. At declaration time,
var
means "use the mutable version" and
let
means "use the immutable version. Copy-on-write ensures you don't mutate an immutable value passed to you. So:
let array = [1, 2, 3]
array += 4 // compiler error
var array2 = array // copy
array2 += 4 // OK
print(array) // [1, 2, 3]
print(array2) // [1, 2, 3, 4]
k

karelpeeters

08/21/2017, 3:34 PM
Well Kotlin doesn't have actual immutability nor any mutating guarantees about methods (yet), so I don't think that would work here.
b

benleggiero

08/21/2017, 3:46 PM
🙏 Valhalla...