gpt4 book ai didi

arrays - 如何在 Kotlin 中定义 funs(函数)数组?

转载 作者:行者123 更新时间:2023-12-02 01:55:52 26 4
gpt4 key购买 nike

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

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

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

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

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

val function = getFunction(funs)
function()

最佳答案

如果您将某些函数定义为

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

关于arrays - 如何在 Kotlin 中定义 funs(函数)数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69610693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com