Array of Units


#1

I’d like to a an array of units, so far I have

fun main(args: Array<String>) {
	val units = arrayOf(println("printFoo"), println("printBar"))

    units[0]
}

When I call “units[0]” i want it to print “printFoo” but it’s not happening, instead, the output is
printFoo
printBar


#2

If you want to pass lambdas as values, you need to use {...} notation.


#3

So you want an array containing a bunch of functions which you can call at a later stage?

In that case you would need something like this

val units = arrayOf({println("printFoo")}, {println("printBar")})

and you can call it using

units[0]()
// or
units[0].invoke()

The reason for this is, if you use your original code, you call println twice with 2 different arguments and store the results of this function call in the array. println does not return anything though, which is not actually true. Every function in Kotlin that has no explicit return type returns the Unit object. That’s the reason why your above code does compile. You just get an array containing Unit twice.
I suggest you take a lookt at higher order functions. There are a lot of useful things you can do with them and understanding them is important to use Kotlin efficiently IMO.

… darksnake beat me to it :wink:


#4

Alright thanks !


#5

If the functions all have the same signature, you can also do this using function references:

typealias Func = (String) -> Unit

fun main(args: Array<String>) {
    val units = arrayOf<Func>(::println, ::println)
    units[0]("printFoo")
    units[1]("printBar")
}