I have a variable that holds a callback, and by default it's value should be null. But this syntax doesn't seem to work.
var callback1 : () -> Unit = null
var callback2 : ((a) -> c, b) -> Unit = null
My current solution is to make sure that callbacks have default implementations.
var callback1 : () -> Unit = { }
var callback2 : ((a) -> c, b) -> Unit = { a, b -> }
This, however, makes it hard to check whether or not the callback was set, and possibly default implementation comes at some cost (is that so?). How to assign a null value to a function type variable in Kotlin?
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!