Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not nullable value required to call 'component1()' function of destructuring declaration initializer

Is it possible to make the following code to compile in Kotlin?

val variable: String? = "string"

val (a, b) = variable?.run {
    1 to 2
}  
like image 769
Diego Marin Santos Avatar asked Jul 11 '26 03:07

Diego Marin Santos


1 Answers

The compiler does not allow destructuring because the expression on the right-hand side is typed as a nullable Pair<Int, Int>?, and it's unclear what values a and b should get in case variable is null.

To solve this, you need to get a not-null expression after =.

There's a lot of different ways to deal with nullable values and produce a not-null value from a nullable one, see: In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

For example, if you want to provide fallback values for a and b, then use the ?: operator as follows:

val (a, b) = variable?.run {
    1 to 2
} ?: (0 to 0)

An alternative, for example, would be to check variable for null first:

val (a, b) = checkNotNull(variable) { "variable should never be null" }.run {
    1 to 2
}
like image 119
hotkey Avatar answered Jul 14 '26 07:07

hotkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!