Skip to content
Advertisement

Return interface implementation with Kotlin and lambda

I have this simple interface :

interface ValidationBehavior {
    fun onValidated()
}

This interface is used in one function of a class :

private enum class BehaviorEnum {
    IDLE,
    NAVIGATEBACK
}

private fun getBehavior(payloadBehavior: String) : ValidationBehavior {
    when(BehaviorEnum.valueOf(payloadBehavior)) {
        BehaviorEnum.IDLE -> return object: ValidationBehavior {
            override fun onValidated() {
                // do some stuff
            }
        }
    }
}

My question is : is there a way to simplify the return statement with a lambda ? I try some stuff like this but it doesn’t work :

return ValidationBehavior{ () -> //do some stuff }

EDIT :

Kotlin supports SAM interfaces now so declaring it like so :

fun interface ValidationBehavior {
    fun operator onValidated()
}

allows us to write :

return ValidationBehavior { //do some stuff }

Advertisement

Answer

No, interfaces written in Kotlin cannot be instantiated with a lambda, that only works for interfaces written in Java. If you want to use lambdas in Kotlin, use the functional type, like in your case () -> Unit instead of ValidationBehavior.

Alternatively, write a method that takes a functional type and wraps it in a ValidationBehavior:

interface ValidationBehavior {

    companion object {
        inline operator fun invoke(fn: () -> Unit) = object: ValidationBehavior {
            override fun onValidated() = fn()
        }
    }

    fun onValidated()
}

private fun getBehavior(payloadBehavior: String) : ValidationBehavior {
    when(BehaviorEnum.valueOf(payloadBehavior)) {
        BehaviorEnum.IDLE -> return ValidationBehavior { /* do stuff */ }
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement