Kotlin null check for multiple nullable var's


#43

It seems to me that this is what the !! operator is meant for. It’s great that the compiler will often verify that you have checked for nullability, but when it can’t, it seems fine for the developer to enforce it.


#44

How about:

@ExperimentalContracts
fun notNull(a: Any?, b: Any?): Boolean {
    contract {
        returns(true) implies (a is Any && b is Any)
    }
    return (a is Any && b is Any)
}

@ExperimentalContracts
fun foo(a: Int?, b: String?): String {
    if (notNull(a, b)) {
        return b.repeat(a)
    }
    return ""
}

#45

@tango24 would it make sense to make your notNull() inline?


#46

It’s normally better to let the JVM handle inlining. In nearly 100% of all cases you only want to use inline if you have to deal with reified types or take a lambda argument. Otherwise there is no real performance gain and you just increase the size of the class file.
Basically you don’t want to use inline when kotlin shows a warning about it :wink:


#47

Inline or not, I just wanted to demonstrate the possibility of using contracts.
In fact, simple null-checks are sufficient and probably faster:

@ExperimentalContracts
fun notNull(a: Any?, b: Any?): Boolean {
    contract {
        returns(true) implies (a != null && b != null)
    }
    return (a != null && b != null)
}