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.