Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple and nice way to increment nullable Int in Kotlin

Tags:

syntax

kotlin

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.

like image 569
Aleš Zrak Avatar asked Jan 12 '18 10:01

Aleš Zrak


People also ask

How do you handle nullable in Kotlin?

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.

What is the correct way to initialize nullable variable in Kotlin?

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.

What is the correct way to initialize a nullable variable?

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.


1 Answers

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
like image 165
crgarridos Avatar answered Oct 01 '22 18:10

crgarridos