How to Use Kotlin's String Interpolation?

10 minutes read

Kotlin's string interpolation is a powerful feature that allows you to embed expressions or variables within a string. It helps in making the code concise and more readable by eliminating the need for concatenation using the + operator. To use string interpolation in Kotlin, you can use the $ sign followed by the expression or variable you want to interpolate.


For example, consider the following code snippet:

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

println("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 $ sign. When the println statement is executed, it will print: "My name is John and I am 30 years old."


String interpolation can also be used with expressions. For instance:

1
2
3
4
val x = 5
val y = 10

println("The sum of $x and $y is ${x + y}.")


In the above example, the expression ${x + y} is interpolated within the string. The println statement will produce: "The sum of 5 and 10 is 15."


Furthermore, you can even perform formatting operations within the interpolated expression by using the % operator. For example:

1
2
3
val price = 9.99

println("The discounted price is $%.2f".format(price))


In the above example, the %.2f format specifier is used within the interpolated expression to format the price value with two decimal places. The println statement will display: "The discounted price is $9.99".


String interpolation makes it easier to embed dynamic values into strings, improving the readability and maintainability of the code.

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
Java to Kotlin: A Refactoring Guidebook

Rating is 4.8 out of 5

Java to Kotlin: A Refactoring Guidebook

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

Rating is 4.7 out of 5

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

5
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.6 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

6
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.5 out of 5

Kotlin Cookbook: A Problem-Focused Approach

7
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Rating is 4.4 out of 5

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

8
Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps

Rating is 4.3 out of 5

Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps


How to format numbers with string interpolation in Kotlin?

To format numbers with string interpolation in Kotlin, you can use the formatting options available in the String class.


Here's an example of formatting numbers using string interpolation in Kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fun main() {
    val intValue = 10
    val floatValue = 10.5
    val doubleValue = 10.56789

    println("Int value: $intValue")            // Output: Int value: 10
    println("Float value: $floatValue")        // Output: Float value: 10.5
    println("Double value: $doubleValue")      // Output: Double value: 10.56789

    println("Int value with leading zeros: %03d".format(intValue))   // Output: Int value with leading zeros: 010
    println("Float value with 2 decimal places: %.2f".format(floatValue))   // Output: Float value with 2 decimal places: 10.50
    println("Double value with scientific notation: %.4e".format(doubleValue))   // Output: Double value with scientific notation: 1.0568e+01
}


In the above example, $intValue, $floatValue, and $doubleValue are used to directly interpolate the variables in the string.


To apply custom formatting, you can use the % followed by the format specifier, such as %03d to display an integer with leading zeros, %.2f to display a float with 2 decimal places, or %.4e to display a double in scientific notation with 4 decimal places.


The format() function is then called on the string, passing the variable that needs to be formatted, to get the desired formatted output.


What is the syntax for string interpolation in Kotlin?

In Kotlin, string interpolation can be done using the $ character followed by the variable name or expression wrapped in curly braces {} within a double-quoted string.


Here is an example of string interpolation in Kotlin:

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

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

println(greeting)


Output:

1
Hello, my name is John and I am 25 years old.


In the example above, the variable name and age are interpolated into the string greeting using $ character and curly braces {}.


How to use functions or methods with string interpolation in Kotlin?

In Kotlin, you can use string interpolation to include function or method calls directly in a string template. Here's how you can do it:

  1. Define a function or method that you want to interpolate in a string. For example:
1
2
3
fun calculateSum(a: Int, b: Int): Int {
    return a + b
}


  1. Create a string template and use the dollar sign ($) followed by the name of the function or method enclosed in curly braces ({}) to interpolate its result. For example:
1
2
3
4
5
val a = 5
val b = 10
val sum = calculateSum(a, b)

val message = "The sum of $a and $b is ${calculateSum(a, b)}"


  1. In the above example, the variable message will be assigned the value "The sum of 5 and 10 is 15" by evaluating the expression inside the curly braces.
  2. You can also perform more complex expressions, function calls with arguments, or even chain multiple method calls within the string interpolation expression. For example:
1
2
3
4
val length = "Hello, World!".length
val uppercase = "Hello, World!".toUpperCase()

val result = "The length is ${"Hello, World!".length} and the string in uppercase is ${"Hello, World!".toUpperCase()}"


In the above example, the variable result will be assigned the value "The length is 13 and the string in uppercase is HELLO, WORLD!".


That's how you can use functions or methods with string interpolation in Kotlin.


How does string interpolation work in Kotlin?

String interpolation in Kotlin allows you to include expressions inside a string literal by prefixing the variable or expression with a dollar sign ($). Here's how it works:

  1. Use string literals enclosed in double quotes (") or triple quotes (""") to define your string.
  2. Inside the string literal, you can embed variables, expressions, or function calls using the $ sign followed by the variable or expression enclosed in curly braces ({ }).
  3. When the string is evaluated and displayed, the variable or expression inside the curly braces is replaced with its value.


Here are a few examples to illustrate string interpolation in Kotlin:

  1. Interpolating simple variables:
1
2
3
4
val name = "John"
val age = 25
val message = "My name is $name and I am $age years old."
println(message) // Output: My name is John and I am 25 years old.


  1. Interpolating expressions:
1
2
3
4
val x = 5
val y = 3
val sum = "The sum of $x and $y is ${x + y}."
println(sum) // Output: The sum of 5 and 3 is 8.


  1. Interpolating function calls:
1
2
3
4
5
6
fun getGreeting(): String {
    return "Hello"
}

val greeting = "${getGreeting()}, world!"
println(greeting) // Output: Hello, world!


In addition to simple variables and expressions, you can also use other Kotlin language features, such as property access, method calls, and even nested expressions, in string interpolation. This makes it a flexible way to create dynamic strings.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To install the Kotlin compiler, you can follow these steps:Firstly, ensure that you have Java Development Kit (JDK) installed on your system. Kotlin requires JDK version 6 or higher to run. Visit the official Kotlin website at kotlinlang.org and navigate to th...
Nullability is a key feature in Kotlin that helps prevent null pointer exceptions. In Kotlin, nullability is explicitly expressed in types, which allows you to handle nullable and non-nullable variables in a clear and concise manner.By default, variables in Ko...
To extract a character from a string in Delphi 7, you can use the indexing notation as follows:Declare a string variable to hold the original string from which you want to extract a character. For example: var originalString: string; Assign a value to the or...