What happens when I override a built-in operator, e.g., to, in Kotlin?

29 Views Asked by At

Kotlin defines an infix operator to for building Pairs, which is basically a shorthand for calling the constructor of Pair. In other words

val pair = "verbose" to true

is the same as

val pair = Pair("verbose", true)

In Kotlin, one can define a custom infix operators as extension functions of a given type, e.g.,

infix fun <T: Any> String.to(t: T) : String = this + (" " + t.toString())

After defining this particular infix operator as an extension function of String, in the following code

val pair = "verbose" to true

pair is no longer a Pair<String, Boolean>, instead it is a String with value "verbose true". This is exactly what I want, but somewhat not what I expect. I would have expected the Kotlin compiler to complain that to has already been defined for all types, and that I can't override it.

Could someone point me to an explanation of why this works, under what conditions am I allowed to do this, and how far the visibility of the custom definition of to reaches?

0

There are 0 best solutions below