In Kotlin, as we can use functions as variables, i tend to replace interfaces with function calls like this:
class A {
private var listener: AA? = null
var callThis: (() -> Unit) ? = null)
fun somethingHere() {
callThis?.invoke()
listener?.callThis2()
}
fun attachListener(listener: AA) {
this.listener = listener
}
interface AA {
fun callThis2()
}
}
class B {
init {
val objectA = A()
objectA.callThis = {}
objectA.attachListener(object : A.AA {
override fun callThis2() {
}
})
}
}
As I'm pretty new to Kotlin, i would like to know the differences and in what scenarios should i use function calls vs interfaces, except for the (obviously) abstraction. Or is it the same, and the function call does exactly the same as anonymous inner classes
The function is called many times, each 100s precisely, and i would like to know, in terms of performance, which on is better
A lambda in Kotlin is compiled to an anonymous inner class. Therefore, the performance of the two scenarios will be exactly the same.