question about nullable types - as an example, let...
# android
a
question about nullable types - as an example, let's say I have a util method in java with signature:
public static void showDialog(@NonNull FragmentActivity activity)
and I call it within a fragment using kotlin as
Util.showDialog(fragment.activity)
. The compiler complains that
Expected: FragmentActivity, Found: FragmentActivity?
Knowing that the activity will not be null when I call the method (i:e I call it right after
onActivityCreated()
), which of the following would be a good way to handle the error: - casting:
fragment.activity as FragmentActivity
- non null assertion:
fragment.activity!!
-
let/if
blocks (but this will hide the exception and hurt me in the long run)
l
activity will be nullable because it's a system type (
Activity!
), you can change the
showDialog()
function to accept
Activity?
and verify inside the function if it's not
a
thanks lucas, that's a good approach, but I stated a contrived example. In the actual util method, I need the activity to be non-null. so I am thinking
!!
is the best way out
👍 1