Kotlin defines an infix operator to
for building Pair
s, 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?