Error operator OR logic


I think that it´s is an bug native of the linguage Kotlin.

val flag : Boolean? = false
if (flag == null || false ){ //The second verification has implicit for flag name.
        LOG = "Fail"
        LOG = "Success"

This not break, but dont return an real result.

If you set explicit param for flag, works normal. But Kotlin doenst must be equals Java :frowning:

if (flag == null || flag == false ){

It´s work!

It´s an bug, all right ?


Your wrong about the assumption that flag == null || false is an implicit form of
flag == null || flag == false.

The or-operator (||) in kotlin as in most languages just combines to Boolean expressions. Therefor your code checks flags == null or false. Since false is never true :wink: the compiler optimizes this to flag == null.
It seems like the compiler does not create a warning for this, but if your using IDEA or any other IDE it should display an inspection for you.


As far as I know, there is almost no any language that allows a kind of syntax like that.

If we interpret flag == null || false in English like you would have expected, it would have meant “flag is null or false”. Here, “is” actually refers to “belongs to one of” instead of “equals”, because “flag” only has one value, while “null or false” has at least two values (unless you expect the compiler to evaluate (null || false), which doesn’t have compatible types).

In Kotlin, “belongs to one of” is called in rather than ==, and “or” should be implemented as a set of multiple possible values rather than a boolean operator, so you could actually write this:

if (flag in setOf(null, false))

Although this is not the most efficient way to do this (not sure if the compiler could optimize in setOf into two simple conditions without allocating an extra Set object), this is intuitive and does exactly what you want.