Mangat Rai Modi
Mangat Rai Modi

Reputation: 5706

Kotlin: extension function vs member function with dispatch reciever

Kotlin has a A.to(that: B) extension function that takes any two types of parameter and return Pair<A,B>. Now I have a class with to function with takes two argments.

Basically the two different to functions have exact syntax and the function in the class is getting masked by the extension one.

Example:

// following return Pair<k,v>
fun convert(value:K, converter: org.jooq.Converter<K,V>) = converter.to(value)

Jooq converter is a fairly popular class to convert between Database compatible class to custom class.

According to Kotlin's documentation, extension functions take priority over the class methods, which doesn't make sense for the extension methods provided by kotlin package as their scope is global. There is qualified-this workaround for outscoping the extension functions but it doesn't seem to be helping here

Edit: fun convert itself is an extension function. Otherwise the member function takes priority.

Upvotes: 0

Views: 551

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

The types as stated in the question don't match: Converter<K, V>.to takes V, not K. So converter.to(value) resolves to the extension method simply because it can't be the member method.

Of course, that means your own answer wouldn't work either; probably you modified some of the types, and if you try converter.to(value) now it should work.

Upvotes: 1

Related Questions