How to Concatenate Strings in Kotlin: Simple Guide
In Kotlin, you can concatenate strings using the
+ operator or string templates with $variable inside a string. Both methods combine strings easily and clearly in your code.Syntax
There are two main ways to concatenate strings in Kotlin:
- Using the
+operator: Joins two or more strings directly. - Using string templates: Insert variables or expressions inside a string using
$variableor${expression}.
kotlin
val first = "Hello" val second = "World" // Using + operator val combined1 = first + " " + second // Using string template val combined2 = "$first $second"
Example
This example shows how to join two strings using both the + operator and string templates. It prints the combined results.
kotlin
fun main() {
val greeting = "Hello"
val name = "Alice"
// Using + operator
val message1 = greeting + ", " + name + "!"
println(message1)
// Using string template
val message2 = "$greeting, $name!"
println(message2)
}Output
Hello, Alice!
Hello, Alice!
Common Pitfalls
Some common mistakes when concatenating strings in Kotlin include:
- Forgetting spaces between words when using
+operator, which causes words to stick together. - Not using curly braces
{}when embedding expressions inside string templates, leading to errors.
kotlin
fun main() {
val word1 = "Good"
val word2 = "Morning"
// Wrong: no space added
val wrong = word1 + word2
println(wrong) // Output: GoodMorning
// Right: add space
val right = word1 + " " + word2
println(right) // Output: Good Morning
val count = 5
// Wrong: missing braces for expression
// val message = "Count is $count + 1" // This prints 'Count is 5 + 1'
// Right: use braces to calculate
val message = "Count is ${count + 1}"
println(message) // Output: Count is 6
}Output
GoodMorning
Good Morning
Count is 6
Quick Reference
Here is a quick summary of string concatenation methods in Kotlin:
| Method | Description | Example |
|---|---|---|
| + operator | Joins strings by adding them | "Hello" + " " + "World" |
| String template | Embed variables or expressions inside strings | "Hello, $name!" or "Sum is ${a + b}" |
Key Takeaways
Use the + operator or string templates to concatenate strings in Kotlin.
String templates with $variable are cleaner and easier to read.
Remember to add spaces manually when using + operator.
Use ${} to embed expressions inside string templates.
Both methods produce the same output but string templates are preferred for clarity.