1

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

1
  • Could you please reformat the code? In it's current state it is kinda hard to read. Thanks Commented May 6, 2016 at 20:55

1 Answer 1

4

A lambda in Kotlin is compiled to an anonymous inner class. Therefore, the performance of the two scenarios will be exactly the same.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.