Mateusz Stefek
Mateusz Stefek

Reputation: 183

How to use extension functions defined in Kotlin interface

In Kotlin, it is possible to declare an extension function in an interface like this:

interface Evaluator {
  fun Double.evaluateY1(): Double
  fun Double.evaluateY2(): Double
}

class EvaluatorImpl : Evaluator {
    override fun Double.evaluateY1(): Double {
        return this + 2.0
    }

    override fun Double.evaluateY2(): Double {
        return this + 3.0
    }
}

Having a receiver and an instance of the interface, how do I invoke such extension function?

I came up with a trick involving the with scope function, but I would prefer something with less indentation.

fun usageExample(evaluator: Evaluator, x: Double) {
  with(evaluator) {
    println("Y1 = ${x.evaluateY1()}. Y2 = ${x.evaluateY2()}")
  }
}

Upvotes: 1

Views: 203

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81859

There's no chance to make it work without getting into the scope of your interface. Using with is the recommended solution. You can use an expression body to make it more concise:

fun usageExample(evaluator: Evaluator, x: Double) = with(evaluator) {
    println("Y1 = ${x.evaluateY1()}. Y2 = ${x.evaluateY2()}")
}

Upvotes: 5

Related Questions