I want to use a higher order function as enum parameter. But this doesn't work. I have the following declaration:
enum class Enum(val someValue: Int, val someMethod: () -> Unit)
{
FIRST_VALUE(0, {method0()}),
SECOND_VALUE(1, {method1()})
fun method0() {
}
fun method1() {
}
}
But method0() and method1() cannot be found. Error is Unresolved reference: method0.
Is it somehow possible to realize this with an enum?
The type of the methods inside Enum is Enum.() -> Unit, not () -> Unit. It will work if you change the parameter type.
Note that you can also use a method reference with Enum::method0, instead of creating a new lambda. It's a bit more readable.
enum class Enum(val someValue: Int, val someMethod: Enum.() -> Unit) {
FIRST_VALUE(0, Enum::method0), // Using a method reference
SECOND_VALUE(1, {method1()})
fun method0() {
}
fun method1() {
}
}
Yes it's possible, but you need to move functions method0 and method1 out of the Enum class:
enum class Enum(val someValue: Int, val someMethod: () -> Unit)
{
FIRST_VALUE(0, ::method0), // pass reference to the function
SECOND_VALUE(1, { method1() }); // pass lambda and call `method1()` function in it
}
fun method0() {
}
fun method1() {
}
You can pass reference to a function as a lambda argument as demonstrated in FIRST_VALUE example, or lambda and call a function in it - demonstrated in SECOND_VALUE example.