【问题标题】:Higher Order Function as Enum paramter高阶函数作为枚举参数
【发布时间】:2019-01-15 08:29:46
【问题描述】:

我想使用高阶函数作为枚举参数。但这不起作用。我有以下声明:

enum class Enum(val someValue: Int, val someMethod: () -> Unit)
{
    FIRST_VALUE(0, {method0()}),
    SECOND_VALUE(1, {method1()})

    fun method0() {

    }

    fun method1() {

    }
}

但是找不到method0()method1()。错误是Unresolved reference: method0

是否有可能通过枚举来实现这一点?

【问题讨论】:

    标签: kotlin enums


    【解决方案1】:

    Enum 中的方法类型是Enum.() -> Unit,而不是() -> Unit。如果您更改参数类型,它将起作用。

    请注意,您也可以使用 Enum::method0 的方法引用,而不是创建新的 lambda。它更具可读性。

    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() {
    
        }
    }
    

    【讨论】:

    • @Sergey 只需添加Enum::method0。感谢您的提醒。
    【解决方案2】:

    是的,这是可能的,但您需要将函数 method0method1 移出 Enum 类:

    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() {
    
    }
    

    您可以将函数的引用作为 lambda 参数传递,如 FIRST_VALUE 示例中所示,或者 lambda 并在其中调用函数 - 如SECOND_VALUE 示例中所示。

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2019-09-22
      • 1970-01-01
      相关资源
      最近更新 更多