How to Perform String Interpolation In Kotlin?

8 minutes read

String interpolation in Kotlin allows you to embed expressions inside a string. This helps create dynamic strings by evaluating and substituting the expressions with their values. To perform string interpolation in Kotlin, you can utilize the following options:

  1. Using the $ character: You can use the $ character followed by the expression to interpolate it directly into the string. For example: val name = "John" val age = 25 val message = "My name is $name and I'm $age years old."
  2. Using the ${} syntax: For more complex expressions or accessing object properties, you can enclose the expression inside ${}. For example: val person = Person("Jane", 30) val message = "My name is ${person.name} and I'm ${person.age} years old."
  3. Escaping the $ character: If you need to use the $ character itself without interpolation, you can escape it by using $$. For example: val price = 10 val message = "The price is $$price."


String interpolation in Kotlin provides a concise and readable way to construct dynamic strings based on variables and expressions.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.7 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

5
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.6 out of 5

Kotlin Cookbook: A Problem-Focused Approach

6
Java to Kotlin: A Refactoring Guidebook

Rating is 4.5 out of 5

Java to Kotlin: A Refactoring Guidebook

7
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.4 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

8
Advanced Kotlin (Kotlin for Developers Book 4)

Rating is 4.3 out of 5

Advanced Kotlin (Kotlin for Developers Book 4)


What is the function of the $ symbol in string interpolation in Kotlin?

In Kotlin, the $ symbol is used in string interpolation to embed variables or expressions directly into a string. By placing a $ before the variable or expression within a double-quoted string, it will be replaced with its value during runtime. Here's an example:

1
2
3
4
5
val name = "John"
val age = 30

val message = "My name is $name and I am $age years old."
println(message)


Output:

1
My name is John and I am 30 years old.


In this example, the $name is replaced with the value of the name variable (which is "John") and the $age is replaced with the value of the age variable (which is 30). This makes it easy to include variables or expressions within a string without having to concatenate them using the + operator.


How to handle null values in string interpolation in Kotlin?

In Kotlin, you can handle null values in string interpolation by using the safe call operator ?. and the Elvis operator ?:.


With the safe call operator ?., you can access properties or call methods on nullable objects without causing a null pointer exception. If the object is null, the result of the expression will be null too.


The Elvis operator ?: allows you to provide a default value in case of a null value. If the expression on the left side of the Elvis operator is null, the expression on the right side will be used as a fallback.


Here's an example that demonstrates how to handle null values in string interpolation:

1
2
3
4
5
6
7
8
val nullableValue: String? = null
val nonNullableValue: String = "Hello"

val combinedValue = "The value is: ${nullableValue?.length ?: "unknown"}"
println(combinedValue) // Output: "The value is: unknown"

val anotherValue = "The value is: ${nonNullableValue?.length ?: "unknown"}"
println(anotherValue) // Output: "The value is: 5" (length of "Hello" is 5)


In the above example, if nullableValue is null, the length will be replaced with "unknown" using the Elvis operator. On the other hand, nonNullableValue is not null, so its length will be used.


By using the safe call operator ?. and the Elvis operator ?:, you can handle null values in string interpolation effectively in Kotlin.


How to perform nested string interpolation in Kotlin?

In Kotlin, nested string interpolation can be performed by utilizing the $ character inside a string enclosed by double quotes ("). Follow the steps below to perform nested string interpolation:

  1. Create a string with the outer and inner interpolated values enclosed by double quotes.
  2. Use the $ character followed by the inner interpolated value inside the outer interpolated value.
  3. Enclose the entire string within another set of double quotes.


Here's an example:

1
2
3
4
5
val outerValue = "Hello"
val innerValue = "World"

val message = "$outerValue, \${$innerValue}!"
println(message)


Output:

1
Hello, ${World}!


By adding a backslash (\) before the $ character, you escape the inner interpolation, preventing it from being evaluated.


What is the performance impact of string interpolation in Kotlin?

String interpolation in Kotlin has a negligible performance impact because it is optimized by the Kotlin compiler.


During compilation, the compiler transforms string interpolation expressions into concatenation operations using a StringBuilder. This optimization reduces the runtime overhead and ensures that string interpolation has comparable performance to traditional concatenation.


The resulting compiled code for string interpolation is efficient and performs well, even with complex expressions or multiple interpolations within a single string. Therefore, developers can freely use string interpolation in Kotlin without significant performance concerns.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

The Kotlin Standard Library functions are a set of utility functions that come built-in with the Kotlin programming language. These functions provide convenient ways to perform common tasks when working with different types of data.To use the Kotlin Standard L...
String resources in Kotlin can be used to store and manage strings separately from your code. It allows for better organization, localization, and reusability of strings throughout your application.To use string resources in a Kotlin file, follow these steps:A...
Retrofit is a widely used networking library in Android development, and it provides a convenient way to consume APIs and perform network operations in your Kotlin projects. Here is a brief explanation of how to perform network operations using Retrofit in Kot...