Caio Costa
03/03/2021, 2:44 AM// 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.Willy Ricardo
03/03/2021, 4:38 AMCaio Costa
03/03/2021, 12:04 PM