About strings concatenation

Currently there is no standard library function to concatenate two strings in a type-safe way.
The String.plus operator accepts Any? (like Java) performing an implicit conversion to string (in my opinion dangerous), moreover there’s not any function like Java String.concat(String).

So I would suggest to restrict the plus operator or, at least, provide a function in standard library like the following:

infix fun String.concat(other: String): String = this + other 

Note: I’m experimenting the latest Kotlin 1.1 version.

2 Likes

We had String.concat before 1.0 was released, but decided not to include it as we already have String.plus operator.

Could you elaborate what are the dangers of having String.plus operator defined that way as it is?

The plus operator converts the operand to a string implicitly, so you cannot detect eventual errors at compile time.

A very simple example. Suppose you have some objects that use a variable/field of type String representing a username, and you concatenate it to some strings. Later, you decide to refactor the code lifting the username in a specific class, maybe a data class Username, then you’ll have no compile time errors for such concatenations.

Kotlin would be a “safe” language, so in my opinion it should promote type-safe operations.

2 Likes

When I want to concat Strings and I doWithString(pojo.name + " " + pojo.value) why is Android Studio proposing “convert concatenation to template” ?

Then it converts to doWithString("${pojo.name} ${pojo.value}") . Why? Are there any speed advantages?

And what about doWithString(pojo.name.plus(" ").plus(pojo.value))

What way is recommended?

I don’t know what your last example is compiled to, but the first 2 are both compiled to use StringBuilder (on the JVM), so there is no difference there.

The suggestion to use templates instead of concatenation is there because templates are more idiomatic in Kotlin. Templates are easier to read in more complex cases than your examples. The suggestion helps you ensure 1 code style is used for both simple and complex string concatenation cases.

2 Likes