https://kotlinlang.org logo
Title
a

Abhi

02/07/2018, 10:04 PM
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

Lucas Ribeiro

02/08/2018, 11:10 AM
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

Abhi

02/08/2018, 6:12 PM
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