hyperoslo / android-playbook

MIT License
6 stars 2 forks source link

Kotlin: Null checks in control statements #22

Open sindrenm opened 8 years ago

sindrenm commented 8 years ago

As far as I can see, there are two main ways of doing null checks in if statements and the like:

fun main(args: Array<String>) {
    val swag: String? = null

    // The King of Rock way
    if (swag?.isNotBlank() ?: false) {
        println("Hello, world!")
    }

    // The standard/Java way
    if (swag != null && swag.isNotBlank()) {
        println("Hello, world!")        
    }
}

Which one do you prefer? Albeit a teensy bit strange, I definitely think I prefer the second example with the Elvis operator.

jeantuffier commented 8 years ago

Even if the second looks more natural, since we use kotlin I think we should go for the real stuff which is the first one. For an easier use, we should create an extension like this :

fun String?.isNotNullorBlanck() : Boolean { 
    return this?.isNotBlank() ?: false
}

and then use it like this :

if (swag?.isNotNullorBlanck()) {
    println("Hello, world!")
}
sindrenm commented 8 years ago

We could create an extension like that, but I don't really think it's even necessary to do so, the swag?.isNotBlank() ?: false version is readable enough for me. Might be because I'm used to doing something like this in JavaScript, though, since in JavaScript, null is “falsy” when used in conditionals:

if (swag || swag.isNotBlank()) {
  ...
}

It's not the same, but it “feels” similar. :smile: