String Templates

A string template concisely displays multiple elements within a string.

A string template inserts an identifier’s contents into a string. To use a string template, put a $ before the identifier name:

// StringTemplates/StringTemplates.kt fun main(args: Array<String>) { val answer = 42 println("Found $answer!") // [1] println("printing a $1") // [2] } /* Output: Found 42! printing a $1 */

You can also achieve this with string concatenation:

// StringTemplates/StringConcatenation.kt fun main(args: Array<String>) { val s = "hi\n" // [1] val n = 11 val d = 3.14 println("first: " + s + "second: " + n + ", third: " + d) } /* Output: first: hi second: 11, third: 3.14 */

Here, we place println()’s argument on two lines to keep the code listing narrow.

You can evaluate and convert an expression by placing it inside ${}:

// StringTemplates/ExpressionInTemplate.kt fun main(args: Array<String>) { val condition = true println( "${if (condition) 'a' else 'b'}") // [1] val x = 11 println("$x + 4 = ${x + 4}") } /* Output: a 11 + 4 = 15 */

To include a special character such as a quote inside a string you can either escape the special character with \ (backslash), or use a string literal in triple quotes:

// StringTemplates/TripleQuotes.kt fun main(args: Array<String>) { val s = "value" println("s = \"$s\".") println("""s = "$s".""") } /* Output: s = "value". s = "value". */
With triple quotes, you insert a value of an expression the same way you do it for a single-quoted string.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.