Start learning free

LESSON 8 OF 348 · WELCOME TO SCALA

String Concatenation in Scala in Scala

Lesson

We can concatenate strings with the plus operator (+).

Here is a program that concatenates the strings "I love coding. " and "It is fun!" and assigns the resulted string to a variable message:

var message = "I love coding. " + "It is fun!"
println(message)

Output:

I love coding. It is fun!

Concatenation with variables:

String concatenation is redundat when used with string literals because we already know what the resulted string would be.

For example, in our program, we could have initialized message directly with the bigger string instead of doing concatenation:

var message = "I love coding. It is fun!"
println(message)

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

For example, I might want to print a specific message about my favorite animal, whatever that is:

var favoriteAnimal = "parrot"

var message = "My favorite animal is the " + favoriteAnimal

println(message)

Output:

My favorite animal is the parrot

The value of message will differ if my favorite animal was "dog" or "cat", but it would still make sense.


Concatenating multiple strings:

We can concatenate as many strings as we want in the same line of code by adding a + before each string:

var animal = "parrot"
var name = "Andy"

println(name + ", that's a nice " + animal + " you got there!")

Output:

Andy, that's a nice parrot you got there!

Be careful to add whitespaces and other characters you want in your message


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 1
    Ctrl + Enter to check

    String Concatenation in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free