18

Learning Kotlin: String Templates

 5 years ago
source link: https://www.tuicool.com/articles/hit/vYBNnqf
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The purpose of this lesson is to show off 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 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 of saying a  Verbatim string , which I didn't know was the official term.

The actual Koan here is about converting 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, if you don't know regular expressions, this could be tougher than it needs to be.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK