Menu
Coddy logo textTech

String Templates

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 36 of 93.

You've already seen string templates in action throughout this course: the $ symbol that lets you embed variables directly inside strings. Let's explore this feature more thoroughly.

String templates allow you to insert variable values into strings using the $ prefix:

fun main() {
    val name = "Alice"
    val age = 25
    println("My name is $name and I am $age years old.")
}
// Output: My name is Alice and I am 25 years old.

For simple variable names, just use $variableName. But when you need to include expressions or access properties, wrap them in curly braces:

fun main() {
    val price = 15
    val quantity = 3
    println("Total: ${price * quantity}")
    println("Next year I'll be ${25 + 1}")
}
// Output:
// Total: 45
// Next year I'll be 26

The curly braces tell Kotlin to evaluate the expression inside before inserting it into the string. This works with any valid expression: arithmetic, function calls, or property access.

If you need to print an actual dollar sign, escape it with a backslash:

fun main() {
    val price = 50
    println("The cost is \$$price")
}
// Output: The cost is $50
challenge icon

Challenge

Easy

Write a function formatReceipt that takes item, quantity, and pricePerUnit and returns a formatted receipt line.

Use string templates with both simple variable insertion ($variable) and expression evaluation (${expression}) to build the receipt string.

Format: The returned string should follow this exact pattern:

[item] x[quantity] = $[total]

Where [total] is the result of multiplying quantity by pricePerUnit.

Parameters:

  • item (String): The name of the item
  • quantity (Int): The number of items purchased
  • pricePerUnit (Int): The price per single item

Returns: A formatted receipt line (String). Format: Apple x3 = $15

Try it yourself

fun formatReceipt(item: String, quantity: Int, pricePerUnit: Int): String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground