简体   繁体   English

我如何在枚举中使用 function 参考?

[英]How can i use function reference inside enum?

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?我可以以某种方式定义 function 以供参考吗? 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 ).此代码根本无法编译( Unresolved reference: predicate )。

Update:更新:

I'am just created companion object:我刚刚创建了伴侣 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> .然后我的 IDE 建议我使用另一种类型KFunction0<(String) -> String> But i can i use function as param here?但是我可以在这里使用 function 作为参数吗?

Your variable is a lambda (just like reference of function) by default you don't need to pass its reference.默认情况下,您的变量是 lambda (就像函数的引用),您不需要传递它的引用。

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.如果您在类/对象中定义了 function,则必须传递它们各自的引用。

PS: Reference of a function generates lambda signature, while lambda has already a lambda signature PS:引用一个 function 会生成 lambda 签名,而 lambda 已经有一个 Z945F3ZFC449518A8736B 签名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM