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 26The 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 $50Challenge
EasyWrite 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 itemquantity(Int): The number of items purchasedpricePerUnit(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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground