This is neat

var func : ((String) -> Unit)? = null

fun main(args : Array<String>) {
  func = { (msg) -> println(msg)}
  func?.invoke(“hello world”)
}

Above code is neat but is there any alternative way to invoke the func function variable?

Does func!!("...") work for you?

var func : ((String) -> Unit)? = null

fun main(args : Array<String>) {
  func = { (msg) -> println(msg)}
  if (func != null)
  func!!(“hello world”)  
}

Yes. func?(“”) doesn’t work though.

Why do you need the if there? You know that func is not null at that point, don't you?

P.S. func?.(“”) should not work, it is not an expression

No, this specific example doesn't need if statement. But in the real world scenario of assigning callback to a property and invoking it later, the option is either

``

func?.invoke()

or

``

if (func != null)
  func!!()

I'd use

``

var func : (String) -> Unit = {}

fun main(args : Array<String>) {
  func = { (msg) -> println(msg)}
  func(“hello world”)
}


instead

Whoa, I didn't know you can assign empty code block to function type.

On the other hand, this doesn’t work

``

var func : (String, Int) -> Unit = {}

fun main(args : Array<String>) {
  func = { (msg, x) -> println(“$msg $x”)}
  func(“hello world”, 10)
}

generates

``

(1, 36) : Expected 2 parameters of types jet.String, jet.Int

at http://kotlin-demo.jetbrains.com/

This is not an empty code block but a function literal with an empty body. It is equivalent to "func = { it -> }"

One day it will work for multiple parameters as well: http://youtrack.jetbrains.com/issue/KT-1949.
Meanwhile, declare the parameters explicitly:

“func = {x, y -> }”

Ah. Thanks for the explanation.