Learning Kotlin: String Templates

Submitted by Robert MacLean on Wed, 06/20/2018 - 09:00
**More Information** * [The code being referenced](https://github.com/Kotlin/kotlin-koans/blob/master/src/i_introduction/_5_String_Templates/n05StringTemplates.kt). * This is the 6th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) The purpose of this lesson is to show off string templating and 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 are used to string templates from C# and JavaScript this should be fairly simple to understand. The fourth example is 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 brought up something I've never heard of, raw strings. Raw strings seem to be the [Python way](https://stackoverflow.com/questions/41359412/python-raw-string-r-flag-equivalent-in-c-sharp) of saying a [Verbatim string](https://stackoverflow.com/a/3312075/53236)... which I didn't know was the official term. The actual Koan here is about converting this `fun getPattern() = """\d{2}\.\d{2}\.\d{4}"""` to a different regular expression, using a string template: fun task5(): String = """\d{2}\s$month\s\d{4}""" It isn't that interesting and really, if you don't know regular expressions this could be tougher than it needs be.