【问题标题】:How do you define an array of funs(functions) in Kotlin?你如何在 Kotlin 中定义一组函数(函数)?
【发布时间】:2021-12-05 04:35:42
【问题描述】:

如何在 Kotlin 中定义一组函数(函数)?

这是我对如何完成的假设......

this.funs = arrayOf : Unit(
    this::openCamera,
    this::sendSMS,
    this::makeCall
        )

如何在运行时将每个数组项作为函数调用?在 forEach() 循环中简单地指定 'funs' 来代替 openCamera()、sendSMS() 和 MakeCall() 是否有效?

或者..这是我调用每个函数的方式吗:

val function = getFunction(funs)
function() 

【问题讨论】:

    标签: arrays function kotlin


    【解决方案1】:

    如果你有一些函数定义为

    fun one()   { print("ONE") }
    fun two()   { print("TWO") }
    fun three() { print("THREE") }
    

    然后你可以创建一个数组为

    fun someFun(){
        val arrayOfFunctions: Array<() -> Unit> = arrayOf(::one, ::two, ::three)
        arrayOfFunctions.forEach { function ->
           function()
        }
    }
    

    【讨论】:

    • 谢谢!那行得通...
    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2019-10-24
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多