Implementing the return interface using Kotlin and lambda

I have this simple interface:

interface ValidationBehavior {
    fun onValidated()
}

This interface is used in one class function:

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 lambda? I try something like this, but this does not work:

return ValidationBehavior{ () -> //do some stuff }
+4
source share
1 answer

No, interfaces written in Kotlin cannot be created using lambda, which only works for interfaces written in Java. If you want to use lambdas in Kotlin, use a functional type, for example, in your case () -> Unitinstead ValidationBehavior.

Alternatively, write a method that uses a functional type and wraps it in 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 */ }
    }
}
+7

Source: https://habr.com/ru/post/1616731/


All Articles