Twitter LogoFacebook Logo
String Templates
Adding Kotlin expressions in a String
By: King

In Kotlin, you can insert expressions (code that can be evaluated and returns a value) inside of a String.

Syntax

$[name_of_variable]

${expression}

Examples

val myAge = 20


println("Hi, I am $myAge years old")

In the example, there is an variable call myAge with the value of 20. Inside the String literal, it used the $ symbol to take in the value of myAge.


The result will be "Hi, I am 20 years old"

fun add(val a: Int, b: Int) {
   return a + b
}

println("5 + 5 is ${ add(5, 5) }.")

In the example, it used the $ and {} symbols to call the add() function and inserted the result into the String literal.


The result is "5 + 5 is 10."

Inserting a "$" Symbol

To insert a "$" symbol into a String, use the follow code:

"${'$'}"

In here, we used a template expression to insert a $ symbol.


Sign In