0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I guess I'm trying to ask why isn't there a += in kotlin
@OrenIshShalom are you sure? Kotlin docs
Worth pointing out that += is two combined operations anyway, plus (which doesn't change, or mutate, the original value) and then the result is assigned to the variable, in place of the original value (which is discarded). Kotlin has some functions that mutate the original (usually a Collection) as well as an equivalent that just creates a copy with changes, but Strings are always immutable (in Java too)
@Alex.T, I think you should post this as an answer. newcomers to Kotlin (like myself) might benefit from this short and simple answer.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.