Start learning free

LESSON 55 OF 348 · STRINGS I

String Concatenation in Kotlin: Using the += Operator

Lesson Read the full explanation

Remember that string concatenation is used to dynamically generate messages that can be different depending on context.

We most often use it with variables, let's check an example:

val adjective = "awesome"
var message = "AlgoCademy is "

// String concatenation & assignment:
message = message + adjective

println(message) // Output: AlgoCademy is awesome

We first concatenate message and favoriteAnimal and then we assign the result to message.


Concatenating with +=

Since this is such a common pattern, there is the += operator which does both the concatenation and assignment in one step.

val adjective = "awesome"
var message = "AlgoCademy is "

// With += operator:
message += adjective

println(message) // Output: AlgoCademy is awesome

Concatenating multiple strings:

We can append as many strings as we want using the += operator:

val name = "Andy"
val pet = "dog"
var message = "Hey, "

message += name
message += "! Nice "
message += pet
message += "!"

println(message) // Output: Hey, Andy! Nice dog!


Assignment
Follow the Coding Tutorial and let's practice with string concatenation!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · STRINGS I

    String Concatenation Ii in Kotlin, explained

    What concatenation with variables looks like

    Concatenation joins strings end to end, and it is most useful with variables, where the final message depends on the data. The + operator joins two strings into a new one:

    val adjective = "awesome"
    var message = "AlgoCademy is "
    
    message = message + adjective
    
    println(message) // AlgoCademy is awesome
    

    Two things happen on the line message = message + adjective. Kotlin first builds a new string from the old message and adjective. Then it stores that new string back in message. The old text is not modified; the variable just points to the new string.

    That detail explains the keywords. message is declared with var because it gets a new value. adjective is declared with val because nothing assigns to it again.

    The += operator

    Updating a variable by adding something to it is so common that Kotlin has a shorthand. message += adjective means exactly the same as message = message + adjective:

    val adjective = "awesome"
    var message = "AlgoCademy is "
    
    message += adjective
    
    println(message) // AlgoCademy is awesome
    

    You can use it as many times as you like to build a longer message in pieces:

    val name = "Andy"
    val pet = "dog"
    var message = "Hey, "
    
    message += name
    message += "! Nice "
    message += pet
    message += "!"
    
    println(message) // Hey, Andy! Nice dog!
    

    Each line appends to whatever the variable holds at that moment. The pieces can be variables or string literals, and the spaces and punctuation have to be part of those pieces. Kotlin never adds a space for you.

    Gotchas

    The variable must be a var

    += on a string assigns a new string to the variable, so the variable must be declared with var. With val, the compiler rejects it:

    val fixed = "abc"
    fixed += "d"
    
    error: 'val' cannot be reassigned.
    

    Other values can join in, if the string comes first

    The left side of + decides what happens. When it is a string, the right side can be any value, and Kotlin converts it to text:

    println("a" + 1 + 2) // a12
    

    Each + works from left to right: "a" + 1 becomes "a1", and then "a1" + 2 becomes "a12". The numbers are not added together first. If the left side is a number and the right side a string, as in 1 + 2 + "a", the compiler reports an error, because Int has no plus that accepts a string. Start with a string, or convert the number with toString(): (1 + 2).toString() + "a" gives 3a. The same applies to variables, so "n=" + n with n = 7 gives n=7.

    Templates are often neater

    For messages with several variables, a string template puts the variables right inside the text. "Hey, $name! Nice $pet!" gives the same result as the four += lines above. This lesson practises +=, and templates are the natural next step when many pieces are involved.

    Many appends in a loop

    Every += builds a new string, so appending thousands of times in a loop copies the growing text each time. For that case, Kotlin offers StringBuilder, whose append changes the same object. For a handful of appends, as in this lesson, += is perfectly fine.

    The exercise, step by step

    The starting code has two variables:

    var message = "Coding is "
    val adjective = "worthwhile"
    
    1. Append the adjective. Write message += adjective. The text becomes Coding is worthwhile.
    2. Append the question tag. Write message += ", isn't it?". The string literal starts with a comma and contains an apostrophe, which needs no escape inside double quotes. The text becomes Coding is worthwhile, isn't it?.
    3. Print the result with println(message).

    The complete solution

    var message = "Coding is "
    val adjective = "worthwhile"
    
    message += adjective
    message += ", isn't it?"
    println(message)
    

    It prints:

    Coding is worthwhile, isn't it?
    

    Common mistakes

    • Printing too early. println(message) shows the text as it is at that line. Before the two += lines it would print only Coding is .
    • Missing spaces and punctuation. The starting text ends with a space, so the adjective joins correctly. The second piece begins with a comma, so no space goes before it.
    • Using = instead of +=. message = adjective replaces the text instead of extending it.
    • Forgetting the quotes around the literal. Without them, , isn't it? is not valid code.

    Key takeaways

    • + joins two strings into a new one.
    • a += b is shorthand for a = a + b, and it needs a to be a var.
    • Strings are never changed in place; the variable gets a new string.
    • Put spaces and punctuation in the pieces yourself.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free