在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.
在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