How to assign a null value to a function type variable in Kotlin?

Solution 1:

Like all variables in Kotlin, function references normally cannot be null. In order to allow a null value, you have to add a ? to the end of the type definition, like so:

var callback1 : (() -> Unit)? = null
var callback2 : (((a) -> c, b) -> Unit)? = null

You will usually need parentheses around the entire function type declaration. Even if it's not required, it's probably a good idea. You will also need to invoke the function using invoke with the null-safe operator:

callback1?.invoke()

The do-nothing implementation approach is probably more convenient in the long run, and seems a bit more "kotlin-y" to me. As with most things in computer science, I wouldn't worry about the performance cost of the default implementation unless you have specific performance data that indicates it's a problem.

One way to determine if the callback has been set without allowing null values would be to use the null object pattern:

val UNSET_CALLBACK1: () -> Unit = {}
var callback1 : () -> Unit = UNSET_CALLBACK1
fun callback1IsSet(): Boolean {
    return callback1 !== UNSET_CALLBACK1
}

Hope this helps!