Search code examples
genericskotlinkotlin-extension

Reference to multiple bounds generic receiver extension function in Kotlin


Has an extension function

fun <T> T.doSomething() where T: A, T: B

If there only one generic bound A, I can use syntax (A::doSomething)(instanceOfA) to reference to the function, but how to do this with multiple bounds?


Example:

interface A, interface B, and a extension function bounded with both interfaces fun <T> T.doSomething() where T: A, T: B.

Now I manage to "override" doSomething if a class extends additional interface C, like class X: A, B, C:

  1. Declare another extension function fun <T> T.doSomething() where T: A, T: B, T: C
  2. Declare doSomething() inside class X

If I use doSomething() in both "override" function directly will cause endless recursion. How can I reference to original fun <T> T.doSomething() where T: A, T: B(like super.doSomething())?


Solution

  • A bit ugly, but

    fun <T> T.doSomething() where T: A, T: B = ...
    
    // calls the first version of doSomething
    fun <T> T.doSomethingHelper() where T: A, T: B = this.doSomething()
    
    @JvmName("doSomethingElse")
    fun <T> T.doSomething() where T: A, T: B, T: C = ... // use doSomethingHelper() here
    

    Without @JvmName I get

    java.lang.ClassFormatError: Duplicate method name&signature in class file Simplest_versionKt