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. 📝
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.
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!".
Placeholders in Kotlin string templates are denoted by the $ symbol, followed by the name of the variable or expression you want to insert.
val age = 25
val greeting = "You are $age years old."
println(greeting) // Output: You are 25 years old.If you have a variable name that starts with a dollar sign, you can escape the placeholder by doubling the dollar sign.
val dollarVariable = "$"
val greeting = "The dollar sign is: $$dollarVariable"
println(greeting) // Output: The dollar sign is: $You can also quote placeholders if you want to include the dollar sign in the output.
val name = "O'Reilly"
val greeting = "The author's name is: ${"$name"}!"
println(greeting) // Output: The author's name is: O'Reilly!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.
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.
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! 🎉