Home > database >  Overloading on reference to method of a particular instance in Kotlin
Overloading on reference to method of a particular instance in Kotlin

Time:10-06

It's clear on how to reference a method of a particular instance: Reference to method of a particular instance in Kotlin

e.g.

val f = a::getItem

However what if getItem is overloaded? I cannot seem to find any material on that.

Let's assume the getItem has the following overloaded functions:

getItem (String) -> Item
getItem (String, Metrics) -> Item

How do I select any particular function by bound instance callable?

CodePudding user response:

The context will determine which overload is chosen. In the case of

val f = a::getItem

The context does not say anything about what type a::getItem should be, so if getItem were overloaded, both overloads would be applicable, and there would be a compile-time error telling you exactly that. Something like:

Overload resolution ambiguity. All these functions match.

  • public fun getItem(name: String): Item defined in ...
  • public fun getItem(name: String, metrics: Metrics): Item defined in ...

If you instead give it some information about the type of f:

val f: (String) -> Item = a::getItem

Then it will pick the correct overload.

  • Related