In this tutorial, you shall learn how to write variables inside a string in Kotlin, using string interpolation, with the help of examples.
Kotlin – Variable inside String
To write or interpolate variables inside a string in Kotlin, write the variable name preceded by the dollar sign $
.
While expanding or interpolating the string, the variable is replaced with its value.
For example, in the following string literal, we have specified the variables x
and y
.
"Your coordinates are ($x, $y)"
And in the following string literal, we have specified the variable $name
in our string.
"Welcome $name"
Examples
1. Write integer variable in string
In the following program, we have integer variables x
, y
. We write these variables inside a string literal using string interpolation $
sign.
Main.kt
fun main() {
val x = 3
val y = 6
val str = "You coordinates are ($x, $y)"
println(str)
}
Output
You coordinates are (3, 6)
2. Write name variable in string
In the following program, we have string variable name
. We write this variable inside a string using string interpolation.
Main.kt
fun main() {
val name = "Arjun"
val str = "Welcome $name"
println(str)
}
Output
Welcome Arjun
Conclusion
In this Kotlin Tutorial, we learned how to write a variable inside a string literal using string interpolation.