Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

Why is it that

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

throws an error, while

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

does not?

like image 817
Rahul Sankhala Avatar asked Dec 17 '25 21:12

Rahul Sankhala


1 Answers

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}"
like image 128
Abby Avatar answered Dec 19 '25 15:12

Abby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!