Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method References to Super Class Method

How to use method references to refer to super class methods?

In Java 8 you can do SubClass.super::method.

What would be the syntax in Kotlin?

Looking forward to your response!

Conclusion

Thanks to Bernard Rocha! The syntax is SubClass::method.

But be careful. In my case the subclass was a generic class. Don't forget to declare it as those:

MySubMap<K, V>::method.

EDIT

It still doesn't work in Kotlin.

Hers's an example in Java 8 of a method reference to a super class method:

public abstract class SuperClass {
    void method() { 
        System.out.println("superclass method()");
    }
}

public class SubClass extends SuperClass {
    @Override
    void method() {
        Runnable superMethodL = () -> super.method();
        Runnable superMethodMR = SubClass.super::method;
    }
}

I'm still not able to do the same in Kotlin...

EDIT

This is an example how I tried to achieve it in Kotlin:

open class Bar {
    open fun getString(): String = "Hello"
}

class Foo : Bar() {

    fun testFunction(action: () -> String): String = action()

    override fun getString(): String {
        //this will throw an StackOverflow error, since it will continuously call 'Foo.getString()'
        return testFunction(this::getString)
    }
}

I want to have something like that:

...
    override fun getString(): String {
        //this should call 'Bar.getString' only once. No StackOverflow error should happen.
        return testFunction(super::getString)
    }
...

Conclusion

It's not possible to do so in Kotlin yet.

I submitted a feature report. It can be found here: KT-21103 Method Reference to Super Class Method

like image 636
Poweranimal Avatar asked Oct 26 '25 22:10

Poweranimal


2 Answers

As the documentation says you use it like in java:

If we need to use a member of a class, or an extension function, it needs to be qualified. e.g. String::toCharArray gives us an extension function for type String: String.() -> CharArray.

EDIT

I think you can achieve what you want doing something like this:

open class SuperClass {
    companion object {
        fun getMyString(): String {
            return "Hello"
        }
    }
}

class SubClass : SuperClass() {
    fun getMyAwesomeString(): String {
        val reference = SuperClass.Companion
        return testFunction(reference::getMyString)
    }

    private fun testFunction(s: KFunction0<String>): String {
        return s.invoke()
    }
}
like image 70
Bernardo Rocha Avatar answered Oct 29 '25 13:10

Bernardo Rocha


Don't know if it is possible to get the reference to super class's function, but here is an alternative to what you want to achieve:

override fun getString(): String = testFunction { super.getString() }
like image 36
Jacky Choi Avatar answered Oct 29 '25 14:10

Jacky Choi