Learning Android Development

Avoid Kotlin’s !! with Common Graceful Error Report Function

When are tempted to just use !! in Kotlin to Ensure Non-Null

Photo by xiaole Zheng on Unsplash

In my journey migrating some code from the App from Android API 29 to Android API 30, I discover some APIs have been improved to indicate nullability. e.g.

public String getStringExtra(String name) {
return mExtras == null ? null : mExtras.getString(name); }

changed to

public @Nullable String getStringExtra(String name) {
return mExtras == null ? null : mExtras.getString(name);
}

Hence our Kotlin code that uses getStringExtra like below will complain error, due to nullable String API can be assigned to a non-nullable String.

private val someID: String by lazy {
intent.getStringExtra(ID_KEY)
}

Quick ways to solve

The quickest way to solve this problem is to use !!, as we’re almost sure it will never be null.

private val someID: String by lazy {
intent.getStringExtra(ID_KEY)!!
}

But it is not so nice, as it will crash the app as it happens. Not graceful to customer.

--

--