String Interpolation

Many programming languages offer some form of “string interpolation”, where strings can contain programming language expressions directly in them. For example, you can do this in JavaScript, using backticks to enclose the string:

let count = 5;
console.log(`The value of count is ${count}`);

This will print the following to the console:

The value of count is 5

Ruby has a similar capability for double-quoted strings:

count = 5
puts "The value of count is #{count}"

Kotlin’s string interpolation syntax is reminiscent of JavaScript’s. However, for a simple variable reference, you can skip the braces and just use $:

  val count = 5

  println("The value of count is $count")

Arbitrary Kotlin expressions can be used with ${} syntax:

  val count = 3

  println("The value of count is not ${count+2}")

This can be very handy for assembling a string from many pieces, compared to using something like StringBuilder in classic Java.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.