Book Image

Kotlin Programming Cookbook

By : Aanand Shekhar Roy, Rashi Karanpuria
Book Image

Kotlin Programming Cookbook

By: Aanand Shekhar Roy, Rashi Karanpuria

Overview of this book

The Android team has announced first-class support for Kotlin 1.1. This acts as an added boost to the language and more and more developers are now looking at Kotlin for their application development. This recipe-based book will be your guide to learning the Kotlin programming language. The recipes in this book build from simple language concepts to more complex applications of the language. After the fundamentals of the language, you will learn how to apply the object-oriented programming features of Kotlin 1.1. Programming with Lambdas will show you how to use the functional power of Kotlin. This book has recipes that will get you started with Android programming with Kotlin 1.1, providing quick solutions to common problems encountered during Android app development. You will also be taken through recipes that will teach you microservice and concurrent programming with Kotlin. Going forward, you will learn to test and secure your applications with Kotlin. Finally, this book supplies recipes that will help you migrate your Java code to Kotlin and will help ensure that it's interoperable with Java.
Table of Contents (21 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

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:

  1. In Kotlin, the template expression starts with a $ sign.
  2. The syntax of string templates is as follows:
$variableName

Alternatively, it is this:

${expression}
  1. 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 ("""):
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