Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - How to correctly concatenate a String

Tags:

string

kotlin

A very basic question, what is the right way to concatenate a String in Kotlin?

In Java you would use the concat() method, e.g.

String a = "Hello "; String b = a.concat("World"); // b = Hello World 

The concat() function isn't available for Kotlin though. Should I use the + sign?

like image 421
Daniele Avatar asked May 25 '17 19:05

Daniele


People also ask

What is the correct way to concatenate the strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

What symbol is used for string concatenation in Kotlin?

As we know, String objects are immutable. With each concatenation using the + operator or plus() method, we get a new String object.

How do you concatenate strings and integers in Kotlin?

To concatenate strings in Kotlin, you can use concatenation operator + .

How do I concatenate two characters to a string?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination).


2 Answers

String Templates/Interpolation

In Kotlin, you can concatenate using String interpolation/templates:

val a = "Hello" val b = "World" val c = "$a $b" 

The output will be: Hello World

  • The compiler uses StringBuilder for String templates which is the most efficient approach in terms of memory because +/plus() creates new String objects.

Or you can concatenate using the StringBuilder explicitly.

val a = "Hello" val b = "World"  val sb = StringBuilder() sb.append(a).append(b) val c = sb.toString()  print(c) 

The output will be: HelloWorld

New String Object

Or you can concatenate using the + / plus() operator:

val a = "Hello" val b = "World" val c = a + b   // same as calling operator function a.plus(b)  print(c) 

The output will be: HelloWorld

  • This will create a new String object.
like image 163
Avijit Karmakar Avatar answered Sep 17 '22 15:09

Avijit Karmakar


kotlin.String has a plus method:

a.plus(b) 

See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/plus.html for details.

like image 42
Harald Gliebe Avatar answered Sep 18 '22 15:09

Harald Gliebe