How can i use function reference inside enum?

Viewed 108

I have next enum declaration:

enum class Foo(val f: (String) -> String)

And next body:

BAR({obj -> obj.toString()}),
FOO({obj -> obj.toString()})
...

Can i somehow define function for reference? Something like this:

private val predicate: (String) -> String = {obj -> obj.toString()}

And next usage:

 FOO(::predicate)

This code don't compile at all (Unresolved reference: predicate).

Update:

I'am just created companion object:

 companion object Predicate {
    private fun predicate(): (String) -> String {
                return {obj -> obj.toString()}
            }
}

And then my IDE suggested me to use another type KFunction0<(String) -> String>. But i can i use function as param here?

1 Answers

Your variable is a lambda (just like reference of function) by default you don't need to pass its reference.

private val predicate: (String) -> String = {obj -> obj.toString()}

enum class Foo(val f: (String) -> String) {
    FOO(predicate),
    BAR(predicate)
}

Works just fine. While if you have function defined in class/objects them you have to pass their respective reference.

PS: Reference of a function generates lambda signature, while lambda has already a lambda signature

Related