String interpolation is a variable substitution with its value inside a string. In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression.
Kotlin string formatting is more powerful than basic interpolation.
Kotlin String Interpolation Example
The example shows how to do string interpolation in Kotlin.
package net.javaguides.kotlin.examples
fun main(args: Array<String>) {
val name = "Ramesh"
val age = 29
println("$name is $age years old")
val msg = "Today is a sunny day"
println("The string has ${msg.length} characters")
}
Output:
Ramesh is 29 years old
The string has 20 characters
The two variables are interpolated within the string; i.e. they are substituted with their values:
println("$name is $age years old")
Here we get the length of the string. Since it is an expression, we need to put it inside the {} brackets:
println("The string has ${msg.length} characters")
Comments
Post a Comment