This is neat


#1

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?


#2

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


#3

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.


#4

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


#5

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!!()


#6

I'd use

``

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

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


instead

#7

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/


#8

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 -> }”


#9

Ah. Thanks for the explanation.