14

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.

Aleš Zrak
  • 361
  • 1
  • 3
  • 14

5 Answers5

21

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
crgarridos
  • 6,873
  • 2
  • 35
  • 53
3

The other answers present shorter alternatives, I'll present how to properly use the basic if-construct:

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

It's much like in Java, you don't have to add any new layer of complication.

Marko Topolnik
  • 179,046
  • 25
  • 276
  • 399
0

Use inc. In Kotlin, all the operators are converted into method call. See here for more details.

var myInt: Int? = 3
myInt = myInt?.inc()
Joshua
  • 4,757
  • 1
  • 23
  • 45
0
var myInt: Int? = 3
myInt = myInt?.inc()

Note that I've assigned the value returned by inc() to myInt, as documentation states the following:

The inc() and dec() functions must return a value, which will be assigned to the variable on which the ++ or -- operation was used. They shouldn't mutate the object on which the inc or dec was invoked.

aga
  • 25,984
  • 9
  • 77
  • 115
0

The best solution is crgarridos' one.

Here is an alternative in case you want to increment by other values:

var myInt: Int? = 1
val n = myInt?.plus(1)
println(n)

This prints:

2
gil.fernandes
  • 9,585
  • 3
  • 41
  • 57