0

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?

oguz ismail
  • 1
  • 16
  • 47
  • 69
tunnuz
  • 23,338
  • 31
  • 90
  • 128
  • 1
    See my answer above. Basically, there is a priority to this. The built in `to` is an implicitly imported extension function, so has a lower priority than the `to` you declared in your own package's scope or imported from somewhere else. – Sweeper Aug 31 '22 at 11:05
  • 1
    Relatedly, I've also [answered](https://stackoverflow.com/q/71588021/5133585) a case where you *cannot* override the existing behaviour of a built-in operator (addition for integers), because the built-in operator is not implemented as an extension function. – Sweeper Aug 31 '22 at 11:11

0 Answers0