Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Learning Kotlin: String Templates

DZone's Guide to

Learning Kotlin: String Templates

Want to learn more about String templating? Here are some examples of string templating with Koan.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:
java ,kotlin ,tutorial ,string

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}