Using String templates in Kotlin
Kotlin packs great features with commonly used data type String. One of the really cool features is String templates. This feature allows Strings to contain template expression.
In Java, you had to use StrSubstitutor (https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StrSubstitutor.html) and a map to go with it. A template expression in Java will look as follows:
Map<String, String> valuesMap = new HashMap<String, String>(); valuesMap.put("city", "Paris"); valuesMap.put("monument", "Eiffel Tower"); String templateString ="Enjoyed ${monument} in ${city}."; StrSubstitutorsub=newStrSubstitutor(valuesMap); String resolvedString =sub.replace(templateString);
Kotlin eases out the pain in writing template expressions and makes it fun, concise, and a lot less verbose.
Using String templates, you can embed a variable or expression inside a string without string concatenation. So, let’s get started!
How to do it...
In the following steps, we will learn how to use String templates:
- In Kotlin, the template expression starts with a
$
sign. - The syntax of string templates is as follows:
$variableName
Alternatively, it is this:
${expression}
- Let's check out a few examples:
- Consider the example of a String template with variable:
fun main(args: Array<String>) { val foo = 5; val myString = "foo = $foo" println(myString) }
The output of the preceding code will be foo = 5
.
- Consider the example of a String template with expression:
fun main(arr: Array<String>){ val lang = "Kotlin" val str = "The word Kotlin has ${lang.length} characters." println(str) }
- Consider the example of a String template with raw string:
- Raw string: A string consisting of newlines without writing
\n
and arbitrary string. It's a raw string and is placed in triple quotes ("""
):
- Raw string: A string consisting of newlines without writing
fun main(args: Array<String>) { val a = 5 val b = 6 val myString = """ ${if (a > b) a else b} """ println("Bigger number is: ${myString.trimMargin()}") }
When you run the program, the output will be Bigger number is: 6
.
How it works...
The use of String template with a variable name is quite straightforward. Earlier, we used to concatenate the strings, but now we can just specify the variable with the $
symbol before it.
When the string template is used as an expression, the expression inside the ${..}
is evaluated first and the value is concatenated with the string. In the preceding example (String template with raw string), the ${if (a > b) a else b}
expression is evaluated and its value, that is 6, is printed with the string.
There’s more...
String templates also come in handy with String properties and functions. Here's an example:
fun main(args: Array<String>) { val str1="abcdefghijklmnopqrs" val str2="tuvwxyz" println("str1 equals str2 ? = ${str1.equals(str2)}") println("subsequence is ${str1.subSequence(1,4)}") println("2nd character is ${str1.get(1)}") }
Here's the output:
str1 equals str2 ? = false subsequence is bcd 2nd character is b