Home > Blockchain >  How to use a globally defined nullable variable as not null in kotlin
How to use a globally defined nullable variable as not null in kotlin

Time:11-23

When writing an implementation in kotlin, I would like to use globally defined variables as non-null. Functionally these variables cannot be null, but technical implementation requires them to be nullable.

The solution I use so far is:

val funtionalValue = if (global.technicalValue != null) global.technicalValue!! else throw someException()

Is there a way to assign the functionalValue without using !! on the globally defined technical value?

CodePudding user response:

There are standard-library functions you might want to use, called checkNotNull and requireNotNull.

val funtionalValue = checkNotNull(global.technicalValue)

This will result in an IllegalStateException being thrown, in case the value is null. requireNotNull will throw an IllegalArgumentException and is better suited to validate function parameters and user input.

If you want to control the exception that is thrown, instead of if and !! you could also use the elvis operator.

val funtionalValue = global.technicalValue ?: throw someException

Thanks @Sweeper for pointing out checkNotNull.

  • Related