如何习惯性地在Kotlin中调用可为空的Lambda? [英] How do I idiomatically call a nullable lambda in Kotlin?

查看:248
本文介绍了如何习惯性地在Kotlin中调用可为空的Lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下lambda:

Given the following lambda:

val lambda: () -> Unit = null

以下哪些调用对于Kotlin来说是空泛的,因为它调用了可为空的lambda?

Which of the following calls is idomatic to Kotlin for calling a nullable lambda?

lambda?.let { it() }

vs

lambda?.invoke()

推荐答案

让我们问一下Kotlin编译器:

Let's ask Kotlin compiler:

 val lambda: (() -> Unit)? = null    
 lambda()

编译器说:

Reference has a nullable type '(() -> Unit)?', use explicit '?.invoke()' to make a function-like call instead

是的,似乎?.invoke()是可行的方式.

So yeah, seems that ?.invoke() is the way to go.

尽管这对我(和编译器)来说似乎都还不错:

Although even this seems fine by me (and by compiler too):

 if (lambda != null) {
      lambda()     
 }

这篇关于如何习惯性地在Kotlin中调用可为空的Lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆