String Templates in Kotlin: Behind the Scenes!

Estefania Cassingena Navone
Techmacademy
Published in
2 min readAug 13, 2018

📃 Meet Templates!

Let’s learn an awesome feature that Kotlin incorporates, String Templates! We can assign dynamic values directly into our strings and print statements in Kotlin using templates.

But what are templates? They are a special syntax in Kotlin used to incorporate variables and expressions into a string so it can be updated dynamically as your code is executed.

Let’s check it out!

📦 Variables

The syntax used to incorporate a variable into a string is a $ followed by the name of the variable.

$<variable>

For Example:

var numZebras : Int = 10println(“The number of Zebras is: $numZebras”) // Notice the Syntax

In this example we insert the value of the variable numZebras in the print statement so this is the final string that will be printed:

The number of Zebras is: 10

💥 Including Expressions

The result of an expression can also be incorporated into a string by using a $ followed by {} and the expression inside the curly braces.

var numAdultZebras : Int = 15
var numBabyZebras : Int = 5
println(“The total number of Zebras is:
${ numAdultZebras + numBabyZebras })
// Notice the syntax

We add the two variables inside the curly braces:

${ numAdultZebras + numBabyZebras }

and this will be printed, the result replaces the expression:

The total number of Zebras is: 20

🔥 More Complex Expressions

You can use more complex expressions inside the curly braces such as if statements:

println("The number of Zebras is greater than 5: 
${if (numZebras > 5) true else false}")
// Notice the if statement

We have this expression:

${if (numZebras > 5) true else false}

It will return true if the number of zebras is greater than 5 and false otherwise.

This will print:

The number is Zebras is greater than 5: true

As you can see, Kotlin provides much more flexibility than java to print strings and to make our daily work easier by improving our workflow and debugging process. Kotlin String Templates are Awesome! 👍

📚Learn More About String Templates & Kotlin!

👋 Now…

I would like to personally invite you to follow Techmacademy to find articles specially written for awesome learners like you.

If you found this article helpful, your claps are very much appreciated to help others who are embarking on this journey.

I would love to read your comments and thoughts.

Follow me on Medium 😃 👍

--

--

Estefania Cassingena Navone
Techmacademy

Udemy Instructor | Developer | MITx 6.00.1x Community TA | Writer @Medium | CS & Mathematics Student | WTM Udacity Scholar