What is the simplest and best readable way to increment nullable Int in Kotlin? Is there any other way than doing this?
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.
type can hold either a string or null , whereas a String type can only hold a string. To declare a nullable variable, you need to explicitly add the nullable type. Without the nullable type, the Kotlin compiler infers that it's a non-nullable type.
Therefore you have to do the initialization var x : String? = null . Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String? . Alternatively you can use lateinit , also on non-nullable types.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
You can call the operator in its invocable way as:
myInt = myInt?.inc()
Note that the inc()
operator does not mutate the value of its receiver but creates a new value. This implies the following statement does not change myInt
:
val myInt: Int? = null
myInt?.inc() // myInt still being null
Neither :
val myInt: Int? = 5
myInt?.inc() // myInt still being 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With