0
0
Kotlinprogramming~5 mins

String concatenation vs templates in Kotlin

Choose your learning style9 modes available
Introduction

We join pieces of text to make one message. String concatenation and templates are two ways to do this simply.

When you want to combine a name and a greeting to say hello.
When you build a sentence using numbers and words together.
When you create messages that include values from variables.
When you want your code to be easy to read and write.
When you need to insert multiple values inside a text.
Syntax
Kotlin
val message = "Hello, " + name + "!"

val messageTemplate = "Hello, $name!"

Use + to join strings in concatenation.

Use $variable inside quotes for templates to insert values.

Examples
This joins "Hello, ", the name, and "!" using +.
Kotlin
val name = "Anna"
val greeting = "Hello, " + name + "!"
This uses a template to insert the name directly inside the string.
Kotlin
val name = "Anna"
val greeting = "Hello, $name!"
Concatenation needs to convert numbers to strings first.
Kotlin
val age = 25
val info = "Age: " + age.toString()
Templates insert numbers directly without conversion.
Kotlin
val age = 25
val info = "Age: $age"
Sample Program

This program shows both ways to create a message with name and age. It prints both results.

Kotlin
fun main() {
    val name = "Sam"
    val age = 30

    // Using concatenation
    val messageConcat = "Name: " + name + ", Age: " + age.toString()

    // Using template
    val messageTemplate = "Name: $name, Age: $age"

    println(messageConcat)
    println(messageTemplate)
}
OutputSuccess
Important Notes

Templates are easier to read and write, especially with many variables.

Concatenation requires converting non-text values to strings first.

Templates can include expressions inside ${} if needed.

Summary

String concatenation joins pieces using + and needs conversion for non-text.

String templates insert variables directly inside strings with $.

Templates make code cleaner and easier to understand.