Learning Kotlin: String Templates

Note *

The purpose of this lesson is to demonstrate string templating. The Koan starts with some interesting examples:

fun example1(a: Any, b: Any) = "This is some text in which variables ($a, $b) appear."
fun example2(a: Any, b: Any) = "You can write it in a Java way as well. Like this: " + a + ", " + b + "!"
fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}"

If you're familiar with string templates from C# and JavaScript, this should be fairly simple to understand. The fourth example is particularly interesting:

fun example4() = """You can use raw strings to write multiline text. There is no escaping here, so raw strings are useful for writing regex patterns—you don't need to escape a backslash by a backslash. String template entries (${42}) are allowed here."""

This introduced a concept I hadn’t heard of before—raw strings. Raw strings seem to function like the Python way of handling verbatim strings, which I didn’t realize was the official term.

The actual Koan here involves converting this:

fun getPattern() = """\d{2}\.\d{2}\.\d{4}"""

into a different regular expression using a string template:

fun task5(): String = """\d{2}\s$month\s\d{4}"""

It’s not especially interesting, and honestly—if you don’t already know regular expressions, this could be more challenging than it needs to be.