Sling Academy
Home/Kotlin/String Interpolation: Dynamic Text in Kotlin

String Interpolation: Dynamic Text in Kotlin

Last updated: November 29, 2024

String interpolation in Kotlin is a powerful feature that allows you to construct dynamic strings concisely and efficiently. It enables the embedding of variables and expressions directly within string literals, making your code easier to read and write.

Understanding String Interpolation

String interpolation in Kotlin is achieved using the $ symbol. By prefixing a variable with $ inside a string literal, you can directly embed its value into the string. Here's a simple example:


val name = "Kotlin"
val greeting = "Hello, $name!"
println(greeting)
// Output: Hello, Kotlin!

In this example, the value of the name variable is directly included in the greeting string.

Embedding Expressions

You can also embed more complex expressions within strings by enclosing them in curly braces {}. This is particularly useful when you need to evaluate expressions or call methods.


val apples = 3
val bananas = 2
println("I have ${apples + bananas} fruits in total.")
// Output: I have 5 fruits in total.

In the above snippet, the expression ${apples + bananas} is evaluated and interpolated into the string.

Using String Templates with Functions

String interpolation becomes even more powerful when used with functions. You can execute functions within an interpolated string and include the result in your output:


fun calculateSum(a: Int, b: Int): Int {
    return a + b
}

val sumMessage = "The sum of 7 and 8 is ${calculateSum(7, 8)}."
println(sumMessage)
// Output: The sum of 7 and 8 is 15.

Here, the function calculateSum is called within the string, and its result is interpolated into the message.

Multiline Strings

Kotlin also supports multiline strings with triple quotes """, and you can interpolate variables and expressions within them:


val multilineText = """
    |Hello, my name is $name.
    |I am learning Kotlin!
""".trimMargin()
println(multilineText)

The trimMargin() function helps to remove leading whitespace using | as a margin prefix.

Escaping the Dollar Sign

If you want to include a literal dollar sign without triggering string interpolation, you can escape it using a backslash (\):


val price = 10
println("The price is \$$price")
// Output: The price is $10

String interpolation in Kotlin allows you to create clean, readable, and dynamic text outputs. By embedding variables and expressions directly into strings, you can simplify your code and focus more on logic rather than managing string concatenations.

Next Article: Finding the Length of a String in Kotlin

Previous Article: Concatenating Strings in Kotlin Made Simple

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin