About strings concatenation


#1

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

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?


#3

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.