Carl Rice

View Original

Kotlin Bricks: One strategy to avoid nullable types

If you use Fragments, imagine this common situation where you passed values in via the appropriate setArguments call. The arguments bundle contains a model that you'll reference all over the fragment code. Grabbing it from the bundle every time could be messy and wasteful, especially if it never null.

See this content in the original post

That might be your first approach, however every time you access model you'll need to dereference it with ? or !!. Since I guaranteed at the top that our app will always pass "model" in the Fragment arguments, we can do something slightly differently to avoid all of that.

See this content in the original post

By using lazy delegates we can make the model property non-null and use the Fragment arguments. This technique is useful in Android subclasses where you don't have much control over the lifecycle, but still want control over the nullability of your properties.

lazy works by waiting until the first time you access a property to actually assign it. This usually works well but you have to be cautious when you first call it. For example, calling the in constructor would cause a NullPointerException because arguments was not set yet.