Topic Overview and Actualization

Are you ready to grasp more of Kotlin's essence? Today, we're turning our focus to string concatenation and interpolation, these are vital operations for creating and modifying strings in Kotlin. We'll journey from the basics to real-world applications. Are you ready? Buckle up!

Introduction to String Concatenation

Just as words form sentences in English, strings can be concatenated to form larger strings in Kotlin. You can use + or += for high-speed concatenation. For larger concatenations, Kotlin presents StringBuilder, our speed master. Let's see these speedy elements in action:

val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName  // Concatenate strings
println(fullName)  // John Doe
var greeting = "Hello, "
greeting += "John Doe"  // Append to a string
println(greeting)  // Hello, John Doe
val builder = StringBuilder()
builder.append("Hello, ").append("John Doe")  // StringBuilder in action
val greeting = builder.toString()
println(greeting)  // Hello, John Doe
Introduction to String Interpolation

While concatenation combines whole strings, interpolation weaves values or variables into strings. Kotlin makes it simple with its $ sign:

val userName = "John Doe"
val greeting = "Hello, $userName"  // User name interpolated in the string
println(greeting)  // Hello, John Doe
val apples = 5
val oranges = 10
val message = "You have ${apples + oranges} fruits in total."  // Expression interpolated in the string
println(message)  // You have total 15 fruits.

In addition, Kotlin can even embed expressions within interpolated strings.

Explicit and Implicit Type Conversion in String Operations

Do you have integers or other non-string types that you want to include in your strings? Worry not! Kotlin implicitly converts them to strings. If you wish, you can explicitly convert them using .toString():

val age = 25
val message = "I am $age years old."  // The integer is implicitly converted to a string
println(message)  // I am 25 years old.
val num = 10
val message = num.toString() + " is my favorite number."  // Explicit conversion using .toString()
println(message)  // 10 is my favorite number.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal