Gabor Varadi
Jul 21, 2017 · 1 min read

Interesting article, although with some experimentation I seem to find that just calling guard will not make your type NonNull, because there is no guarantee that you return; when the given item was null.

So instead of

val thing: String? = null
val notNullThing = thing.guard { return }
notNullThing?.trim(); // <-- ?. is needed!

You’d need to do the following:

val thing: String? = null
val notNullThing = thing.guard { return } ?: return; //<--redundant
notNullThing.trim(); // <-- ?. is not needed

In which case the guard statement is useful if you want to execute multiple things after the ?: block

val thing: String? = null
val
notNullThing = thing.guard { println("Blah"); } ?: return;
notNullThing.trim();

But I’m new to Kotlin, so who knows :D

)
    Gabor Varadi

    Written by

    Android dev, `Zhuinden`, or ‘EpicPandaForce’ @ SO. Extension function fan #Kotlin, dislikes multiple Activities/Fragment backstack.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade