Learn
Using Text Variables
String Templates

An alternative to String concatenation is a syntax known as String templates. Many developers prefer String templates over String concatenation for its conciseness and efficiency. Take a look at the difference:

Concatenation: "Hello, " + variableName + "!"

Template: "Hello, $variableName!" 

String templates contain a String with any variable names preceded by a $ symbol. Notice how in contrast to String concatenation, we don’t need to specify whitespace, thus saving keystrokes and limiting the amount of code we write.

Assume we’re building the following program for a travel company that provides a user with their itinerary:

val passengerName = "Alex" val trainNumber = 2039 val timeOfDeparture = "16:00" val timeOfArrival = "20:00" println("Mrs. $passengerName will be on the $trainNumber train departing at $timeOfDeparture to DevCity and arriving at $timeOfArrival.")

Each variable gets evaluated within the text producing the final itinerary information:

Mrs. Alex will be on the 2039 train departing at 16:00 to DevCity and arriving at 20:00.

String templates are widely used and are often the preferred syntax by Kotlin developers. Keep in mind that String concatenation is also a valid strategy, so it’s important to be familiar with both when collaborating with others.

Instructions

1.

In Plant.kt, set up a String template using the given variables to output the following text:

An [plant] in a [potSize] inch pot must be watered every [dayNum] days.

Make sure to replace the brackets around each variable with the correct String template notation.

Folder Icon

Take this course for free

Already have an account?