lannyf
lannyf

Reputation: 11025

How to simplify this kotlin code if it needs both boolean and nullable checking?

A dataConfig object has a nullable Boolean field urlIsabled, and would like to return based on whether the dataConfig.urlIsabled == null or the negative of the the dataConfig.urlIsabled

val result = if (dataConfig.urlIsabled != null) (dataConfig.urlIsabled != true) else true)

could it be simplified?

Upvotes: 1

Views: 286

Answers (3)

Ilya
Ilya

Reputation: 23115

Plot a simple truth table:

| dataConfig.urlIsabled | result |
|-----------------------|--------|
|        null           |  true  |
|        true           |  false |
|        false          |  true  |
|-----------------------|--------|

So the result is true in all cases except when urlIsabled equals true. Thus it can be expressed as:

val result = dataConfig.urlIsabled != true

Upvotes: 4

Pawel
Pawel

Reputation: 17248

You try to return true if dataConfig.urlIsDisabled is null or false.

Just invert the logic and return false if value is equal to true:

val result = !(dataConfig.urlIsabled == true)

Upvotes: 1

Boken
Boken

Reputation: 5446

Can be simplified as:

val result = dataConfig.urlIsabled in listOf(false, null)

Upvotes: 0

Related Questions