I've updated my Kotlin project to use support library 27.0.0. When I try to get the Activity context in a Fragment I'm getting this error:
> Type mismatch: inferred type is FragmentActivity? but Context was expected
It's safe to assume that activity
or context
is not null in any of the fragment's lifecycle methods (between onAttach
and onDetach)
. In this case
context!!
seems better because if it's null when it's definitely NOT supposed to be null, something is terribly wrong and you should just crash.
In asynchronous callbacks of course check for null.
For me "!!" is never and option.
Then by all means abstract it away. This is what I did in my BaseFragment
class:
val context: Context
@JvmName("getContext2")
get() = getContext()!!
And then at use site:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
context // Context is *never* null here.
}
fun someCallbackMethod() {
if (isAdded) {
context // Context is also not null here.
} else {
// But it is null here.
}
}
Unfounded null-checks everywhere are just as bad as the non-null assert operator.
This is equal to what would happen before support library 27 where nullability annotations were added. You could access context
anywhere and it would crash if it were null and dereferenced.
Update: Recent support library introduced methods for this case:
The difference from my suggestion above is that these methods will throw IllegalStateException
instead of KotlinNullPointerException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With