OrenIshShalom
OrenIshShalom

Reputation: 7112

kotlin string concatenation no side effect

Why is string concatenation kept without side-effects?

fun main() {
    var s1 = "abc"
    val s2 = "def"
    s1.plus(s2)
    println(s1)
    // s1 = s1.plus(s2)
    // println(s1)
}

I expected abcdef, but got just abc. The commented code works fine, but seems awkward.

Upvotes: 0

Views: 254

Answers (2)

Alex
Alex

Reputation: 90

As this answer shows. Your plus operation returns the concatenated string independent from the given strings. This is because strings are immutable in Kotlin. An alternative is to use CharLists or buffers.

Note that immutability has some serious benefits. With immutablility it is no problem to give away your references to immutable objects because nobody can change the object. You need to change the reference in your model to hold a new value. This way it helps a lot to guarantee consistency and integrity in your model. Also note that immutable objects are threadsafe for that reason.

Upvotes: 2

Jens Baitinger
Jens Baitinger

Reputation: 2365

The plus() method (or the + operator, which is basically the same thing in kotlin) is returning the concatenated string. So by calling

s1.plus(s2)
//or
s1 + s2

you concatenate these strings but you throw away the result.

Upvotes: 3

Related Questions