kotlinnull

Kotlin: coding discussion: elegant way to check multiple variables which could null


I use Kotlin to Programm Android Apps. For null-pointer safety one needs to check if all references are non-null. However if only one is null then we should inform the user that something went wrong.

It is important for me to program in a concise readable manner.

I am looking for a short and easy understandable solution.

The standard way would be:

if  (b != null && a != null && c !=null ...) println ("everything ok.")
else println("Something went wrong")

Solution

  • Here are two concise expressions you can use.

    This one valuates to true when all variables are non-null:

    listOf(a, b, c).all { it != null }
    

    This one evaluates to true when any variable is null:

    listOf(a, b, c).any { it == null }
    

    In context, this is how you can use the second one:

    println(if (listOf(a, b).any { it == null })) "Something went wrong"
            else "Everything ok.")