Hey folks, how are you doing? I'd like to know if...
# android
c
Hey folks, how are you doing? I'd like to know if there's any advantage in using method references instead of Interface references when it comes to Listeners. Let's take for example the snippet of code below:
Copy code
// Using an Interface
interface ABC {
    fun doIt()
}

private fun doIt() {
    val doItListener = object : ABC {
        override fun doIt() {
            println("Do it!")
        }
    }
    //Passing the Interface reference
    Main(doItListener)
}

// Class which the instruction will be executed in(Interface reference)
class Main(listener: ABC) {
    init {
        listener.doIt()
    }
}

----------------------------------------------------

// Using Method reference
private fun doIt2() {
    println("Do it!")
}

private fun callDoIt2() {
    //Passing Method reference
    Main(::doIt2)
}

// Class which the instruction will be executed in(Method reference)
class Main(task: () -> Unit) {
    init {
        task()
    }
}

----------------------------------------------------

//Running
fun main() {
    doIt()
    callDoIt2()
}
I ran both ways and both worked. But in my real scenario, the "Main" classes are Adapters and both doIt() and doIt2() would be instructions executed when users clicked an item of a list. Both examples would be triggered by such action individually. But my main question is: Does passing a reference of a method located at an Activity actually take with it any kind of information of such Activity which in this case is where it's located at? What do you think is the best approach in this case: A listener created from an Interface or putting all instructions inside a method and then passing its reference to an Adapter or whatever class it is. I'd like to hear from you guys. Thanks in advance.
w
Second way is basically creating lambda, which is actually runnable. So the difference berween those two only the way you code. First one is tidier Second one is easier There is no difference in performance. Personally I prefer first one. Both doesn't contains parent class information where it constructed. They are different object. As long as no value stored. There is no relation but stacktrace.
c
Oh thank you @Willy Ricardo. I saw the second way being used really often on the project I work so it got me thinking about it. I find the second way more elegant and more concise but i had to ask other people about it. Appreciate your answer 👍