Kotlin String Templates 🎯

beginner
11 min

Kotlin String Templates 🎯

Welcome to our comprehensive guide on Kotlin String Templates! In this lesson, we'll walk you through the basics and advanced concepts of working with strings in Kotlin. By the end of this tutorial, you'll be well-equipped to use string templates in your own projects. 📝

What are Kotlin String Templates? 📝

String templates are a powerful feature in Kotlin that allow you to embed expressions within string literals. This is particularly useful when you need to construct strings based on runtime values.

kotlin
val name = "John Doe" val greeting = "Hello, $name!" println(greeting) // Output: Hello, John Doe!

In the example above, we've created a variable name with the value "John Doe". We've then created a new variable greeting that contains a string literal with a placeholder $name. When we print the greeting variable, Kotlin replaces the placeholder with the value of the name variable, producing the output "Hello, John Doe!".

Understanding Placeholders 📝

Placeholders in Kotlin string templates are denoted by the $ symbol, followed by the name of the variable or expression you want to insert.

kotlin
val age = 25 val greeting = "You are $age years old." println(greeting) // Output: You are 25 years old.

Escaping Placeholders 📝

If you have a variable name that starts with a dollar sign, you can escape the placeholder by doubling the dollar sign.

kotlin
val dollarVariable = "$" val greeting = "The dollar sign is: $$dollarVariable" println(greeting) // Output: The dollar sign is: $

Quoting Placeholders 📝

You can also quote placeholders if you want to include the dollar sign in the output.

kotlin
val name = "O'Reilly" val greeting = "The author's name is: ${"$name"}!" println(greeting) // Output: The author's name is: O'Reilly!

String Interpolation 💡

Kotlin also supports a more advanced method of string construction called string interpolation, which allows you to use curly braces {} instead of the dollar sign.

kotlin
val name = "John Doe" val age = 25 val greeting = "Hello, $name. You are $age years old." println(greeting) // Output: Hello, John Doe. You are 25 years old. val formattedGreeting = "Hello, ${name.toUpperCase()}. You are $age years old." println(formattedGreeting) // Output: Hello, JOHN DOE. You are 25 years old.

In the example above, we've used curly braces to interpolate the name and age variables. We've also demonstrated how you can apply functions directly to the variables within the curly braces.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the output of the following code?

That's all for our Kotlin String Templates tutorial! By now, you should have a good understanding of how to use string templates and string interpolation in your Kotlin projects. Happy coding! 🎉