I sometimes see statements like somevariable.value?.add() What purpose does the question mark serve? (Sorry, at the time of post I had no idea this was Kotlin, I thought it was java)

推荐答案

Kotlin treats null as something more than the source of null-pointer exceptions.

在您的代码片段中,somevariable.value是"可空类型",例如MutableList?Axolotl?.MutableList不能是null,但MutableList?可能是null.

通常,要在对象上调用函数,需要使用..

对变量、参数或属性调用函数的一个选项

  • If the value is null, your function call is ignored, and null is the result
  • 如果该值不是null,则函数调用将正常进行

So, in your case:

  • 如果somevariable.valuenull,则跳过add()呼叫

  • 如果somevariable.value不是null,则对somevariable.value进行add()调用

Kotlin相关问答推荐

测试Compose Multiplatform UI时,为另一个文件设置ComposeRule()

如何在Kotlin中为两个数据类创建可重用的方法?

Kotlin和JavaFX:绑定行为奇怪

在Kotlin中求n个ClosedRange实例相交的最常用方法是什么?

Kotlin异步不并行运行任务

如何在 Kotlin 中为类方法调用传递变量

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

ActivityResultContracts TakePicture 结果总是返回 false

Jetpack Compose:当状态从另一个活动改变时强制重组

如何在 Kotlin 中不受约束?

为什么没有remember 的 mutableStateOf 有时会起作用?

使用 Kotlin 协程时 Room dao 类出错

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

来自类型参数的属性的自定义 getter

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

Kotlin boxed Int 不一样

有没有办法在数据类构建时转换属性的值?

Kotlin中的测试无法访问受保护(protected)的方法

Jetpack Compose-居中文本

为什么在 Kotlin 中return可以返回一个return?