6

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 }

2 Answers 2

7

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 */ }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

would it be acceptable to create the interface in Java and use it in Kotlin ? In order to avoid to create the inline function and being able to use the interface directly with lambdas
If you or your team find it okay, then I guess it would be ok. However consider just dropping the interface and using the functional type.
any use of java-interop for hacking kotlin is not-idiomatic, obviously. A factory function is the best solution
0

I know this question is quite old, but there is a way to do it in Kotlin. Look at fun interface kotlin there is a simple way to do what you want.

2 Comments

Yes, I edited my post a few months ago saying exactly that.
Oh right, didn't see sorry

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.