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

Time:02-11

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?

CodePudding user response:

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()
  • Related