https://kotlinlang.org logo
#android
Title
# android
p

Paul Dhaliwal

08/07/2019, 8:13 PM
In a lot of cases on android calls like this come up
ContextCompat.getColor(context, color.colorPrimaryDark)
which gives the error “type mismatch Required Context, Found Context?” I can get around this error by using “context as Context” or “context!!“, however these don’t feel like the right approaches. The Kotlin doc says !! is for “NPE-lovers” which I am not lol. What’s the best way to handle these situations? I’m still new to Kotlin and development in general and don’t want to develop any bad habits. Thanks!
j

jw

08/07/2019, 8:14 PM
context!!
is fine. there's probably also
requireContext()
wherever you're calling this from
the APIs were designed incorrectly
p

Paul Dhaliwal

08/07/2019, 8:40 PM
Ah okay. Thanks a lot!
a

Aslam Hossin

08/08/2019, 2:10 AM
I have already faced the same problem then implement like below. Is it the right way?
j

jw

08/08/2019, 2:18 AM
No
At least, not unless you expect context to be null and want to actually default to
null
in that case. But that seems exceedingly unlikely and even in the case where it is likely you probably want to fix your design so that the code bails much earlier.
👍 1
a

ahulyk

08/09/2019, 12:44 PM
requireContext()
is better than
context!!
from my point of view
2 Views