Rahul Sankhala
Rahul Sankhala

Reputation: 31

Why does println() throw an error in one case but not in another?

Why is it that

println(Int.MIN_VALUE + " " + Int.MAX_VALUE)

throws an error, while

println("" + Int.MIN_VALUE + " " + Int.MAX_VALUE)

does not?

Upvotes: 3

Views: 86

Answers (1)

Abby
Abby

Reputation: 1836

As mentioned in the comments, your two statements call different plus functions. The plus function is a binary operator function, which means that it can be called using the infix notation a + b. This will call the operator function on a, with b as the argument. In your example, this means that

"" + Int.MIN_VALUE

calls the plus defined by String which has String.plus(other: Any?) as its method signature. As mentioned by the documentation, it

Returns a string obtained by concatenating this string with the string representation of the given other object.

This means that it will get the String representation of Int.MIN_VALUE, by calling the toString() method.

On the other hand,

Int.MIN_VALUE + ""

calls the plus defined by Int which limits the type of its argument and cannot be applied to a String, and thus Kotlin will throw an error.


As a side remark, you should probably use string templates anyway:

"${Int.MIN_VALUE} ${Int.MAX_VALUE}"

Upvotes: 3

Related Questions