Search⌘ K

Solution Review: Embed a Variable in a String

Understand how to embed variables directly into strings using Scala's s string interpolator. This lesson helps you practice combining variables like name and age into a single string output with concise syntax to improve your string formatting skills.

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.

Scala
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.