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?
In an effort to rid the world of NullPointerException , variable types in Kotlin don't allow the assignment of null . If you need a variable that can be null, declare it nullable by adding ? at the end of its type. Declares a non- null String variable.
Kotlin neither allows null values to be passed as parameter values nor allows null object references unless you specify that a variable can be null . In other words, Kotlin makes you tell the compiler "this (or that) variable can be null ." Such variables are referred to as nullable values.
Functions as variables. Functions in Kotlin are simply another data type. You can assign them to variables and constants just as you can any other type of value, such as an Int or a String . This function takes two parameters and returns the sum of their values.
Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With