在Kotlin中增加nullable Int的最简单、可读性最好的方法是什么?除此之外还有别的办法吗?

var myInt: Int? = 3
myInt = if(myInt!=null) myInt+1 else null

This is quite fine if myInt is simple variable, but it can grow very long when myInt is some longer expression.

推荐答案

You can call the operator in its invocable way as:

myInt = myInt?.inc()

注意,inc()运算符does not改变其接收器的值,但创建新值.这意味着以下语句不会改变myInt:

val myInt: Int? = null
myInt?.inc() // myInt still being null

Neither :

val myInt: Int? = 5
myInt?.inc() // myInt still being 5

Kotlin相关问答推荐

如何避免使用公共类实现内部接口

如何在Android应用判断上运行多个查询

try 一次性插入多条记录时,JOOQ连接为空错误

Kotlin中反射中Int到可空Double的隐式转换失败

如何从 Period.between() 返回的字符串中提取信息? (Kotlin )

在kotlin中匹配多个变量

在 Compose 中使用 Text() 时如何获取文本的大小?

使用 Compose for Desktop Bundle 文件

如果不为空,则为 builder 设置一个值 - Kotlin

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

Saripaar formvalidation 在 kotlin 中第二次不起作用

OnClickListener 未在 ConstraintLayout 上触发

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

比较 Kotlin 中的可比对象列表

如何在 kotlin 的片段类中更改 ActionBar 标题?

Kapt不适用于Android Studio 3.0中的AutoValue

封闭 lambda 的隐式参数被shadowed

添加抽象的私有getter和公共setter的正确方法是什么?

Kotlin out-projected 类型禁止使用

Kotlin Flow 收集后无法执行代码