Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kotlin Programming Cookbook

You're reading from   Kotlin Programming Cookbook Explore more than 100 recipes that show how to build robust mobile and web applications with Kotlin, Spring Boot, and Android

Arrow left icon
Product type Paperback
Published in Jan 2018
Publisher
ISBN-13 9781788472142
Length 434 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Aanand Shekhar Roy Aanand Shekhar Roy
Author Profile Icon Aanand Shekhar Roy
Aanand Shekhar Roy
Rashi Karanpuria Rashi Karanpuria
Author Profile Icon Rashi Karanpuria
Rashi Karanpuria
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Installation and Working with Environment FREE CHAPTER 2. Control Flow 3. Classes and Objects 4. Functions 5. Object-Oriented Programming 6. Collections Framework 7. Handling File Operations in Kotlin 8. Anko Commons and Extension Function 9. Anko Layouts 10. Databases and Dependency Injection 11. Networking and Concurrency 12. Lambdas and Delegates 13. Testing 14. Web Services with Kotlin 15. Other Books You May Enjoy

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
You have been reading a chapter from
Kotlin Programming Cookbook
Published in: Jan 2018
Publisher:
ISBN-13: 9781788472142
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image