In this section, we will learn what the String Template is and how to use it in Kotlin.
What is String Template in Kotlin?
Kotlin String Template is a way of creating a string value using the values of other variables or from the result of an expression.
Basically, when we want to mix in the value of a variable as part of a new string value, we can use the string template.
Kotlin String Template Declaration Syntax:
“ ${variableName}”
${}
: in order to mix in the value of a variable or an expression into the process of creating a string value, we use this symbol within a pair of double quotation and then within the curly braces we put the name of a variable or the expression we want to take its value and make it as part of the string value we’re creating.
Note that before or after the ${} we can put other string values as well.
Also, if we only want to mix in the value of a variable into the string, we can remove the {}
part and only prefix the target variable with the $
sign.
For example:
“ The name is: $firstName”
Here the firstName is a variable and we want to mix in its value into this string.
Example: Assigning String Template to Variable
fun main(){ var fullName = "John Doe" var age = 100 var result = "The name is: $fullName the age is: ${age}" println(result) }
Output:
The name is: John Doe the age is: 100
As you can see, String Templates help us to involve the value of variables in the process of creating a new string value in Kotlin.
So here we’ve created a new string value using the values of the fullName and age variables and then stored the result in to the result
variable, which we then passed to the println function in order to see the result.
Example: passing String Template as Argument to Functions
fun main(){ var fullName = "John Doe" var age = 100 printName("The name is: ${fullName} the age is: ${age}") } fun printName(value:String){ println(value) }
Output:
The name is: John Doe the age is: 100
The purpose of using String Template is to create a new string value using the values of other variables. After the string value is created, it doesn’t matter where we want to send this value! It could be a variable of type String or as the argument of a function that needs a string value!
Note: It’s OK if you’re not familiar with functions yet! In the Kotlin function section, we’ve explain this concept in great details.