How to Use String Interpolation In Kotlin?

10 minutes read

String interpolation in Kotlin allows you to embed expressions inside string literals. This feature makes it easier to build strings dynamically by merging values from variables or expressions into a single string without using concatenation operators.


To use string interpolation in Kotlin, you need to follow these steps:

  1. Define a string literal using double quotes (" ").
  2. Inside the string, enclose the expression you want to interpolate within curly braces ({ }).


Here's an example:

1
2
3
4
5
6
val name = "Alice"
val age = 25

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

println(message)


In the code above, the variable name holds the value "Alice," and the variable age holds the value 25. By using string interpolation ($name and $age), we can embed the values directly into the string.


The output of running this code will be:

1
My name is Alice and I am 25 years old.


You can also perform operations or call functions within the interpolated expressions. For example:

1
2
3
4
5
6
val a = 10
val b = 5

val result = "The result of $a + $b is ${a + b}."

println(result)


In the code above, the expression ${a + b} performs the addition operation and embeds the result into the string.


The output of running this code will be:

1
The result of 10 + 5 is 15.


String interpolation in Kotlin provides a concise and readable way to construct strings. It simplifies string concatenation and enhances the readability of your code by reducing clutter.

Best Kotlin Books to Read in November 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.9 out of 5

Kotlin Cookbook: A Problem-Focused Approach

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Rating is 4.6 out of 5

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

6
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.5 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

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

Rating is 4.4 out of 5

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

8
Java to Kotlin

Rating is 4.2 out of 5

Java to Kotlin

9
Kotlin Essentials (Kotlin for Developers)

Rating is 4.1 out of 5

Kotlin Essentials (Kotlin for Developers)


How to format numbers using string interpolation in Kotlin?

In Kotlin, string interpolation is done using the '$' symbol followed by the variable or expression inside curly braces '{ }'. To format numbers, you can use the following syntax:

  1. Formatting Integers:
1
2
3
4
5
val number = 123456
val formattedNumber = "Formatted Number: $number"
val commaFormattedNumber = "Comma Formatted Number: ${String.format("%,d", number)}"
println(formattedNumber)
println(commaFormattedNumber)


Output:

1
2
Formatted Number: 123456
Comma Formatted Number: 123,456


  1. Formatting Floating-Point Numbers:
1
2
3
4
5
val floatValue = 1234.56789
val formattedFloat = "Formatted Float: $floatValue"
val roundedFloat = "Rounded Float: ${String.format("%.2f", floatValue)}"
println(formattedFloat)
println(roundedFloat)


Output:

1
2
Formatted Float: 1234.56789
Rounded Float: 1234.57


In the above examples, String.format() function is used to format the numbers. It takes a formatting pattern as the first argument. You can customize the formatting pattern according to your needs. For more details on formatting patterns, you can refer to the Java documentation on formatting numbers using String.format().


What is the recommended way to perform string interpolation in Kotlin?

In Kotlin, the recommended way to perform string interpolation is by using string templates.


String templates allow you to embed expressions or variables directly inside a string, making it easy to construct dynamic strings without explicitly concatenating the parts.


To use a string template, you need to prefix the string with the "$" symbol and enclose any variables or expressions to be inserted within curly braces { }.


Here's an example:

1
2
3
4
5
6
val name = "Alice"
val age = 25

val message = "Hello, my name is $name and I am $age years old."

println(message) // Output: Hello, my name is Alice and I am 25 years old.


In the above example, the variables name and age are directly embedded within the string message using the $ syntax.


What are the limitations of string interpolation in Kotlin?

There are a few limitations of string interpolation in Kotlin:

  1. Complex expressions: String interpolation allows simple expressions like variable values inside a string using the $ sign. However, it does not support complex expressions or calculations. If you need to perform complex operations, you would need to use string concatenation or format strings instead.
  2. Lack of formatting options: Kotlin's string interpolation does not provide formatting options like specifying field width, precision, or padding. If you require specific formatting, you would need to use the format strings or other formatting mechanisms.
  3. Limited type coercion: Kotlin's string interpolation automatically converts basic types (like numbers) to strings. However, it has limited type coercion capabilities. If you need to interpolate a custom object or a non-string value, you might need to manually convert it to a string before interpolation.
  4. Limitation for certain characters: In string interpolation, the $ dollar sign is used to denote the start of an expression to be interpolated. However, if you want to include a dollar sign as part of the string literal itself, you need to escape it with a backslash. This can lead to confusion or escaping errors in complex string literals.
  5. Compilation impact: String interpolation is a compile-time feature. The interpolated values are resolved at compile time, which means the interpolated string is finalized during the compilation phase. Consequently, you cannot change the interpolated values dynamically during runtime.


It's worth noting that many of these limitations can be overcome by using format strings, which provides more control and flexibility over string interpolation.


How to escape characters in an interpolated string in Kotlin?

To escape characters in an interpolated string in Kotlin, you can use the backslash () character followed by the character you want to escape. Here are some examples:

  1. Escaping double quotes:
1
2
val name = "John"
val message = "My name is \"$name\"."


  1. Escaping backslashes:
1
2
val filePath = "C:\\Program Files\\Sample\\file.txt"
val text = "The file is located at: $filePath"


  1. Escaping special characters:
1
2
val specialCharacter = '\$'
val message = "This is a special character: \\$specialCharacter"


In the above examples, the backslash tells Kotlin to treat the following character as a literal character and not as part of the string interpolation.


What is the syntax for string interpolation in Kotlin?

In Kotlin, you can perform string interpolation using the ${} syntax.


Here's an example:

1
2
3
4
val name = "John"
val age = 25

val sentence = "My name is $name and I am $age years old."


In the above example, the variables name and age are interpolated within the string using the ${} syntax. The variable values will be inserted into the string resulting in the final sentence value: "My name is John and I am 25 years old."

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To call a Kotlin function from JavaScript, you can use the Kotlin/JS plugin that allows you to compile Kotlin code to JavaScript. First, define your Kotlin function in a Kotlin file using the external keyword to tell the Kotlin compiler that this function will...
To replace a variable name with its value in Swift, you can use string interpolation. By placing a backslash followed by parentheses and the variable name inside a string, you can replace the variable name with its actual value. For example: let name = "Jo...
In Elixir, you can truncate a string using the String.slice/2 function. This function takes two arguments: the string to be truncated and the maximum length of the truncated string. Here's an example of how to use it: string = "This is a long string th...
To use a Kotlin function in Java, you can follow these steps:Create a Kotlin function that you want to use in Java. For example, let's consider a simple function named printMessage() that prints a message. fun printMessage() { println("Hello, world...
To run Kotlin on Ubuntu, you can follow these steps:Install Java Development Kit (JDK): Since Kotlin runs on the Java Virtual Machine (JVM), you need to have Java installed on your system. Open a terminal and run the following command to install the default JD...
Working with Android extensions in Kotlin allows you to leverage the power of Kotlin's extension functions to easily enhance the functionality of Android classes. Here's how you can work with Android extensions in Kotlin.To create an Android extension,...