Solution Review: Embed a Variable in a String

In the following lesson, we will go over the solution of the challenge: Embed a Variable in a String.

We'll cover the following

Task

In this challenge, you were provided two variables and you had to embed them in a string.

Solution

The first thing you had to figure out, was that the s string interpolator can be used to embed variables into strings.

print(s.....)

Next, you needed to write the required string in a print statement. To embed name and age in the string you had to insert a $ followed by the variable name at the location where you wanted to embed the variables.

print(s"$name is $age years old.")

You can find the complete solution below:

You were required to write the code on line 4.

Press + to interact
val name = "Ben"
val age = 18
print(s"$name is $age years old.")

Now let’s move on to string interpolation with f in the next lesson.