Lodea
Lodea

Reputation: 189

Is it possible to make a variable that contains a reference of a function?

for example:

fun aFunc() {
    print("hello")
}

fun main() {
    val test = aFunc //<-- this does not compile

    test()
}

Why is it not possible to make test equal to a reference of aFunc in this case, and is there a correct way to do it?

Upvotes: 0

Views: 32

Answers (1)

Jan B&#237;na
Jan B&#237;na

Reputation: 7218

Yes it is, you can either reference the function directly or create new function which calls the other one, both ways here:

val test = ::aFunc
val test2 = { aFunc() }
  
test()
test2()

Upvotes: 1

Related Questions