Labs ICT
โญ Pro Login

String Templates

String templates are one of those Kotlin features you'll wonder how you lived without. No more clunky concatenation with plus signs โ€” just drop a variable right into your string.

Basic string templates

Use the $ symbol to insert a variable directly into a string.


fun main() {
  val name = "Alice"
  println("Hello, $name!")
}
    

Kotlin replaces $name with its value. Clean, right?

Try it Yourself โ†’

Expressions in templates

Need to do more than just insert a variable? Wrap any expression in ${}.


fun main() {
  val a = 10
  val b = 5
  println("$a + $b = ${a + b}")
}
    

Anything inside ${} is evaluated and the result is inserted into the string.

Try it Yourself โ†’

Calling methods in templates

You can call functions and access properties inside ${} too.


fun main() {
  val word = "kotlin"
  println("'$word' has ${word.length} letters")
  println("Uppercase: ${word.uppercase()}")
}
    
Try it Yourself โ†’

Multiline strings

Use triple quotes """ for strings that span multiple lines. They preserve spacing.


fun main() {
  val message = """
    Hello,
    This is a multiline
    string in Kotlin!
  """
  println(message)
}
    

You can use trimIndent() to remove the extra indentation.


fun main() {
  val message = """
    Hello,
    This is a multiline
    string in Kotlin!
  """.trimIndent()
  println(message)
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

How do you include a variable in a Kotlin string?