Noam Silverstein
Noam Silverstein

Reputation: 839

Is a non-null object from intent?.extras? nullable?

Lets assume, there is a non-null enum MainFlag object ( like enum class MainFlag { PARAM1, PARAM2 }) in an Activity by lateinit var:

private lateinit var flag: MainFlag

Furtheron, I get that later in the onCreate() like:

flag = intent?.extras?.getSerializable(ARG_FLAG) as MainFlag

and I used to use this flag in that activity on several places with null-checks

flag?.let{
  //..
}

but then Android Studio complains:

Unnecessary safe call on a non-null receiver of type MainActivity.Companion.MainFlag

I am not sure using it without null checks, because if intent?.extras? fails, flag will not be set, thus null?

Upvotes: 0

Views: 958

Answers (3)

Roland
Roland

Reputation: 23312

If you are sure that intent?.extras?.getSerializable(ARG_FLAG) will never be null (and also none of the intermediate objects: intent and intent.extras), then you can keep everything as is and just use flag.let { ... instead of flag?.let { ....

If there is a chance that any of those is null, then you have to use a MainFlag?-type for your flag, e.g.:

private var flag : MainFlag? = null // having null in place basically makes the lateinit meaningless and rightfully lateinit does not allow nullable types

flag = intent?.extras?.getSerializable(ARG_FLAG) as? MainFlag

... or risk a TypeCastException when keeping as MainFlag.

The reason why Android Studio complains about the unnecessary safe call, is, that you specified the type as non-nullable MainFlag (indirectly via your as MainFlag-cast). So if you access flag it must already be there and it must be not-null (you said it so). The code however will fail at the cast, if there was a null-value involved, i.e. the cast to the non-nullable type could not succeed.

Upvotes: 0

Ronak Doshi
Ronak Doshi

Reputation: 155

First of all you have to declare the variable as

private lateinit var flag: MainFlag?

or

private var flag: MainFlag? = null

then you can set the value of flag like this

flag = intent?.extras?.getSerializable(ARG_FLAG) as? MainFlag

Now the flag variable is nullable. So you need to check for nullable everywhere in the code like this:

flag?.let{
  //..
}

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157467

yes it can be null. You are getting the warning because you are down casting to a not nullable type

intent?.extras?.getSerializable(ARG_FLAG) as MainFlag

should be

intent?.extras?.getSerializable(ARG_FLAG) as? MainFlag

Upvotes: 3

Related Questions