Kotlin – Place variables in String

Place variables in a string in Kotlin

To place variables in a string in Kotlin, you can use $ symbol followed by the variable name in the string.

For example, to place the variable firstname in a greeting string, it is as shown in the following.

val firstname = "Apple"
val greeting = "Hello $firstname"

Examples

Place firstname variable in Greeting string

In the following program, we take a string value in firstname variable, and then use $ symbol to place our variable in a greeting message string.

Kotlin Program

fun main() {
    val firstname = "Apple"
    val greeting = "Hello $firstname"
    println(greeting)
}

Output

Hello Apple

Place integer variable in string

We can also place integer variables in a string as shown in the following program.

Kotlin Program

fun main() {
    val quantity = 50
    val result = "We have a stock of $quantity apples."
    println(result)
}

Output

We have a stock of 50 apples.