Kotlin String Templates
String templates, also known as string interpolation, are one of Kotlin's most convenient features. They allow you to embed expressions directly into string literals, making your code more readable and concise compared to traditional string concatenation.
Introduction to String Templates
In many programming languages, combining strings with variables or expressions requires concatenation using special operators (like +
in Java). Kotlin simplifies this process with string templates, which allow you to include variable references and expressions directly within string literals.
String templates make your code:
- More readable
- Less error-prone
- More concise
- Easier to maintain
Basic String Templates
The most basic use of string templates involves including a variable directly in a string by prefixing the variable name with a dollar sign ($
).
val name = "Alex"
println("Hello, $name!") // Output: Hello, Alex!
val age = 28
println("I am $age years old") // Output: I am 28 years old
This simple syntax works with any variable, whether it contains a string, number, or other data type.
Using Expressions in String Templates
For more complex operations, you can include expressions by wrapping them in curly braces ${}
:
val a = 10
val b = 20
println("The sum of $a and $b is ${a + b}") // Output: The sum of 10 and 20 is 30
val isAdult = true
println("User status: ${if (isAdult) "Adult" else "Minor"}") // Output: User status: Adult
You can include any valid Kotlin expression inside the curly braces, including:
- Arithmetic operations
- Function calls
- Conditional expressions
- Property access
Accessing Object Properties
You can directly access object properties in string templates:
data class User(val name: String, val age: Int)
val user = User("Maria", 32)
println("User: $user.name is ${user.age} years old") // INCORRECT: Outputs "User: Maria.age is 32 years old"
println("User: ${user.name} is ${user.age} years old") // CORRECT: Outputs "User: Maria is 32 years old"
Notice that in the first example, $user.name
is interpreted as the string representation of $user
followed by the literal text .name
. When accessing properties, always use the curly braces ${}
to ensure correct evaluation.
Escaping Dollar Signs
If you need to include a literal dollar sign in your string, you can escape it with a backslash:
val price = 9.99
println("The item costs \$$price") // Output: The item costs $9.99
Multi-line String Templates
String templates work equally well in multi-line strings (triple-quoted strings):
val name = "Sarah"
val email = "[email protected]"
val message = """
Dear $name,
Thank you for your registration.
We have sent a confirmation email to ${email.uppercase()}.
Best regards,
The Team
""".trimIndent()
println(message)
Output:
Dear Sarah,
Thank you for your registration.
We have sent a confirmation email to [email protected].
Best regards,
The Team
Real-world Examples
Example 1: Formatting User Information
fun formatUserInfo(name: String, age: Int, email: String): String {
return """
User Profile:
-------------
Name: $name
Age: $age
Email: $email
Account type: ${if (age >= 18) "Adult" else "Minor"}
""".trimIndent()
}
val userInfo = formatUserInfo("James Smith", 25, "[email protected]")
println(userInfo)
Output:
User Profile:
-------------
Name: James Smith
Age: 25
Email: [email protected]
Account type: Adult
Example 2: Building HTML Content
data class Product(val name: String, val price: Double, val inStock: Boolean)
fun generateProductHtml(product: Product): String {
return """
<div class="product ${if (product.inStock) "available" else "sold-out"}">
<h2>${product.name}</h2>
<p class="price">$${product.price}</p>
<p class="status">${if (product.inStock) "In Stock" else "Out of Stock"}</p>
</div>
""".trimIndent()
}
val laptop = Product("Laptop Pro", 1299.99, true)
println(generateProductHtml(laptop))
Output:
<div class="product available">
<h2>Laptop Pro</h2>
<p class="price">$1299.99</p>
<p class="status">In Stock</p>
</div>
Example 3: Logging with Context
enum class LogLevel { INFO, WARNING, ERROR }
fun log(level: LogLevel, message: String, context: Map<String, Any> = mapOf()) {
val timestamp = java.time.LocalDateTime.now()
val contextString = if (context.isEmpty()) "" else " - Context: ${context.entries.joinToString { "${it.key}=${it.value}" }}"
println("[$timestamp] ${level.name}: $message$contextString")
}
// Example usage
log(LogLevel.INFO, "User logged in", mapOf("userId" to 123, "method" to "email"))
log(LogLevel.ERROR, "Payment failed", mapOf("orderId" to "ORD-456", "reason" to "insufficient_funds"))
Output (timestamp will vary):
[2023-06-15T14:23:45.123] INFO: User logged in - Context: userId=123, method=email
[2023-06-15T14:23:45.124] ERROR: Payment failed - Context: orderId=ORD-456, reason=insufficient_funds
Best Practices
-
Use templates for readability: Prefer string templates over concatenation for better readability.
kotlin// Instead of this:
val message = "Hello, " + name + "! You have " + count + " notifications."
// Use this:
val message = "Hello, $name! You have $count notifications." -
Use curly braces for complex expressions: Always wrap expressions and property accesses in curly braces.
kotlin// Use this:
"The result is ${number * multiplier}"
// Not this:
"The result is $number * $multiplier" // This would print "The result is 5 * 3" -
Format multi-line strings consistently: Use
trimIndent()
ortrimMargin()
to manage indentation in multi-line strings. -
Be mindful of performance: For strings that are constructed in loops or hot code paths, consider using
StringBuilder
instead of repeatedly creating new strings.
Summary
Kotlin string templates provide a powerful and readable way to create dynamic strings by embedding expressions directly in string literals. They support:
- Simple variable references using
$variable
- Complex expressions using
${expression}
- Usage in both regular strings and multi-line strings
- Character escaping with the backslash (
\
)
String templates make your code more concise and easier to read compared to traditional string concatenation, especially when working with multiple variables or expressions.
Exercises
-
Create a function that takes a list of numbers and returns a string showing the sum, average, minimum and maximum values using string templates.
-
Write a program that formats a receipt with a list of items, their prices, and a total sum using string templates and multi-line strings.
-
Create a function that generates an email message using string templates, including personalized information like name, subscription type, and renewal date.
Additional Resources
- Kotlin Official Documentation on Strings
- Kotlin Playground: Try Kotlin Online
- Kotlin by Example: String Templates
With string templates, you'll find string manipulation in Kotlin to be much more intuitive and readable compared to many other languages. Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)