samedi 26 octobre 2019

Check if expression is null in Kotlin, Lua-style?

In Lua (which is rarely used outside of development in Corona SDK), you can evaluate ANY expression in an if statement as follows:

  1. If expression is null, will return false
  2. If expression is the boolean value false, will return false
  3. Everything else will return true

Examples

if (1) // true
if ("Hello World") // true
if (instanceOfSomeRandomClass) // true
if ( [2, null, "foo"] ) // true
if (thisFunctionCallWithReturnNull()) // false
if (0 == 1) // false

if also happens to be an expression in Kotlin, so combining these features, I can see make creative ways to use it.

Is there an equivalent in Kotlin?

I know you can always manually check if (expression != null) and there's nothing wrong with that, but if (expression) is lazier, and I like being lazy :)

Aucun commentaire:

Enregistrer un commentaire