Home > OS >  How do you define an array of funs(functions) in Kotlin?
How do you define an array of funs(functions) in Kotlin?

Time:10-18

How do you define an array of funs(functions) in Kotlin?

This is my assumption of how it would be done...

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

How would I invoke each array item as a function at runtime? Would simply specifying 'funs' in place of either openCamera(), sendSMS(), and MakeCall() in a forEach() loop work?

or.. is this the way that I would invoke each function:

val function = getFunction(funs)
function() 

CodePudding user response:

If you had some functions defined as

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

Then you can create an array of these as

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

CodePudding user response:

you can use the sealed class as event listener and constructor invoke fun for the corresponding class instance (below is a very simple example, you can modify the sealed class according to your requirement you can also use invoke function/companion object and much more )

import java.util.*
sealed class Num{
    class One:Num()
    class Two:Num()
    class Three:Num()
}

fun onEvent(event: Num) {

    when (event) {
        is Num.One -> println("One")
        is Num.Two -> println("Two")
        is Num.Three -> println("Three")

    }
}

fun main(args: Array<String>) {

    val sc = Scanner(System.`in`)
    println("Enter event name '1' for One, '2' for Two, '3' for Three:")
    var choice = sc.next()
    if (choice[0] == '1')
        onEvent(Num.One())
    if (choice[0] == '2')
        onEvent(Num.Two())
    if (choice[0] == '3')
        onEvent(Num.Three())
}
  • Related