[英]Why do I have to return Unit.INSTANCE in a void kotlin function, when called from Java, and not NULL?
When having a function, for example:当有一个函数时,例如:
fun doSomething(action:() -> Unit) {
action.invoke()
}
if I call this from Java the code needs to be:如果我从 Java 调用它,代码需要是:
doSomething(() -> {
//do something
return Unit.INSTANCE
})
I have seen code instead using我已经看到代码而不是使用
doSomething(() -> {
//do something
return null
})
Does it affect sending null
instead of Unit.INSTANCE
?它会影响发送null
而不是Unit.INSTANCE
吗? Do Kotlin perform more things by validating that UNIT instance is returned instead? Kotlin 是否通过验证返回的 UNIT 实例来执行更多操作?
I think most of the time it will not really matter whether null
or Unit.INSTANCE
is used.我认为大多数时候使用null
还是Unit.INSTANCE
并不重要。 However as there is at least 1 case where such a null
is not desirable, you should probably always use Unit.INSTANCE
then.但是,由于至少有 1 种情况不需要这样的null
,因此您可能应该始终使用Unit.INSTANCE
。
One such made-up example where not returning Unit.INSTANCE
will cause a problem is the following:一个不返回Unit.INSTANCE
会导致问题的Unit.INSTANCE
示例如下:
fun doSomething(action:() -> Unit) {
action.invoke() logReturnTime("after action invocation")
}
infix fun Unit.logReturnTime(msg : String) { TODO("logging return time $msg") }
If you would call this and return null
you would get an IllegalArgumentException
, whereas the code would run without problem if you use Unit.INSTANCE
.如果您调用它并返回null
您将得到一个IllegalArgumentException
,而如果您使用Unit.INSTANCE
,代码将毫无问题地运行。
That having said, I don't believe this is a good example, but it clearly shows, if anyone operates on that Unit
, then it could fail, so you probably better always use Unit.INSTANCE
and you are safe, regardless on what the receiver does with your function.话虽如此,我不认为这是一个很好的例子,但它清楚地表明,如果有人对该Unit
,那么它可能会失败,所以你最好总是使用Unit.INSTANCE
并且你是安全的,无论是什么接收器与您的功能有关。
Any method in Kotlin returns a value. Kotlin 中的任何方法都会返回一个值。 "void" methods always return the one instance of the type Unit
which is Unit.INSTANCE
. “作废”方法总是返回类型的一个实例Unit
是Unit.INSTANCE
。 You can obmit the return type unit in the declaration but implicitly it is added and the value is returned at the end of the method.您可以在声明中省略返回类型单元,但隐式添加它并在方法末尾返回值。 https://kotlinlang.org/docs/reference/basic-syntax.html https://kotlinlang.org/docs/reference/basic-syntax.html
So when calling the Kotlin method from Java code, you need to fullfill the same contract and return something.所以当从 Java 代码调用 Kotlin 方法时,你需要填写相同的契约并返回一些东西。 If you return null
is is a null reference to the type Unit
.如果返回null
则是对类型Unit
的空引用。 Just because it is better, to avoid null references, in case a caller would like to act on the result of your method, you should avoid returning null
and return Unit.INSTANCE
instead.仅仅因为它更好,为了避免空引用,万一调用者想要对您的方法的结果进行操作,您应该避免返回null
并返回Unit.INSTANCE
。 Yes, this case is unlikely, but will cause the most annoying error.是的,这种情况不太可能发生,但会导致最烦人的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.