Avatar ·

How to properly concatenate strings in Kotlin? Comparison of methods and best practices

Hello everyone! I've just started learning Kotlin and encountered a problem with string concatenation. In Java, I was used to using the "+" operator or StringBuilder for complex cases. But in Kotlin, I see several ways and don't understand which one is correct and efficient.\n\nFor example, I have this code:\n\n```kotlin\nval firstName = "Ivan"\nval lastName = "Petrov"\nval age = 30\n\n// Method 1: + operator\nval message1 = "Hello, " + firstName + " " + lastName + "! You are " + age + " years old."\n\n// Method 2: string templates\nval message2 = "Hello, $firstName $lastName! You are $age years old."\n\n// Method 3: StringBuilder\nval sb = StringBuilder()\nsb.append("Hello, ")\nsb.append(firstName)\nsb.append(" ")\nsb.append(lastName)\nsb.append("! You are ")\nsb.append(age)\nsb.append(" years old.")\nval message3 = sb.toString()\n```