0

It causes discomfort when you can do that:

val string = " abc "
val integer = 8
val result = string + integer

and can't do:

val result = integer + string

It has hidden meaning or it's an omission?

4
  • 3
    I think it's because it could be unclear. If you do string + integer it's clear that you want to return a string with the string representation of the integer appended. If you do integer + string it could mean either return a string with the string representation of the integer prepended or it could mean that you want to parse a number from the string and add that to the integer. Commented Feb 26, 2016 at 16:12
  • For example Scala do it without any problem and has override "+": def +(other: String): String = String.valueOf(self) + other Commented Feb 26, 2016 at 16:43
  • @NiceTheo Kotlin isn't trying to be Scala, and for well defined reasons does not allow things implicitly or unclear. Your example is unclear. plus you should be using string templates instead of + for this case. Commented Feb 26, 2016 at 18:45
  • 1
    Why? questions about design should be in discussion forums, an issue in youtrack.jetbrains.com (as a feature suggestion if you wanted), or kotlin slack channels. Commented Feb 26, 2016 at 18:47

1 Answer 1

3

Kotlin is static typed language and in basicly you can't add String to Integer. But there are possible to overload operators, so we can now.

In case when we want add any object to string, it's clear: every object can be implicitly converted to String (Any#toString())

But in case of Int + smthg it's not so clear, so only Int + kotlin.Number is defined in standard library.

I suggest to use string interpolation:

val result = "${integer}${string}"

Or define own overloaded plus operator:

operator fun Int.plus(string: String): String = string + this
Sign up to request clarification or add additional context in comments.

4 Comments

But isn't integer + string just as clear as integer + double? If you add a Double to an Integer the result is a Double so why wouldn't adding a String to an Integer result in a String?
s/string + this/toString() + string/
The plus operator could also be an extension to Any? to work for doubles, etc.: operator fun Any?.plus(string: String) = toString() + string
This is too ambiguous for the stdlib. And does not fit how other things work in stdlib that require conversion first. You can easily taint your own library with all sorts of implied conversions on operators, but that shouldn't be done for everyone who doesn't want that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.