0
0
Kotlinprogramming~5 mins

String templates and interpolation in Kotlin

Choose your learning style9 modes available
Introduction

String templates let you put values right inside text easily. This makes your messages clear and quick to write.

When you want to show a user's name inside a greeting message.
When you need to include numbers or results inside a sentence.
When building dynamic messages that change based on data.
When formatting output for logs or reports with variable info.
Syntax
Kotlin
val message = "Hello, $name!"
val info = "You have ${count + 1} new messages."

Use $variableName to insert simple variables.

Use ${expression} to insert calculations or more complex code.

Examples
Insert a simple variable name inside the string.
Kotlin
val name = "Anna"
val greeting = "Hi, $name!"
Calculate sum inside the string using ${}.
Kotlin
val apples = 3
val oranges = 5
val total = "Total fruits: ${apples + oranges}"
Use \$ to show a literal dollar sign before a variable.
Kotlin
val price = 9.99
val message = "Price is \$$price"
Sample Program

This program uses string templates to show a greeting with the user's name, number of items, and total cost. It also shows how to print a dollar sign.

Kotlin
fun main() {
    val user = "Sam"
    val items = 4
    val pricePerItem = 2.5
    val totalCost = items * pricePerItem

    val message = "Hello, $user! You bought $items items. Total cost: \$$totalCost"
    println(message)
}
OutputSuccess
Important Notes

Remember to escape the dollar sign \$ if you want it to appear as a normal character.

String templates work only inside double quotes "", not single quotes.

Summary

String templates let you put variables or expressions inside strings easily.

Use $variable for simple variables and ${expression} for calculations.

Escape dollar signs with \$ to show them literally.