简体   繁体   English

如何在Kotlin中为函数类型变量赋值空值?

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

I have a variable that holds a callback, and by default it's value should be null. 我有一个包含回调的变量,默认情况下它的值应为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? 如何在Kotlin中为函数类型变量赋值空值?

Like all variables in Kotlin, function references normally cannot be null. 与Kotlin中的所有变量一样,函数引用通常不能为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: 您还需要使用带有null-safe运算符的invoke来调用该函数:

callback1?.invoke()

The do-nothing implementation approach is probably more convenient in the long run, and seems a bit more "kotlin-y" to me. 从长远来看,无所事事的实现方法可能更方便,对我来说似乎更“kotlin-y”。 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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM