Learning Kotlin: String Templates

Submitted by Robert MacLean on Wed, 06/20/2018 - 09:00

More Information

The purpose of this lesson is to show off string templating and the Koan starts with some interesting examples

  1. fun example1(a: Any, b: Any) =
  2.         "This is some text in which variables ($a, $b) appear."
  3.  
  4. fun example2(a: Any, b: Any) =
  5.         "You can write it in a Java way as well. Like this: " + a + ", " + b + "!"
  6.  
  7. 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

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

This brought up something I've never heard of, raw strings. Raw strings seem to be the Python way of saying a Verbatim string... 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:

  1. 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.