2

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?

SlandShow
  • 443
  • 3
  • 13

1 Answers1

1

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

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
  • But what if i need this function inside enum? Is it possible? – SlandShow May 12 '20 at 05:48
  • @SlandShow companion object is set up after the enum has been initialized for the purpose that you can use the enum inside it. Like this: https://stackoverflow.com/a/53524017/11377112 – Animesh Sahu May 12 '20 at 06:04
  • If i will use companion object with function, then i need to change type of lambda to `KFunction0<(String) -> String>`. – SlandShow May 12 '20 at 06:13
  • @SlandShow why that wouldn't even register. A KFunction0 is a lambda that takes no argument and returns a value in your case it is like: `() -> (String) -> String` – Animesh Sahu May 12 '20 at 06:24