Does as? in a if statement insure that the instance inside the block isn't null inside all the if block?

Viewed 41

I know that if i assign the as? to a variable so the compiler won't bother about safe cast issue. For example:

w:Wolf? = Wolf()
wolf = w as? Wolf

Now i can use variable wolf to call any public member of Wolf without using a question mark (no need for safe call)

but if the as? is inside an if block and item variable not being assign. For example:

  if (item as? CountryDataItem != null)
    {
           // code that is using *item*
    }

    else{
   } 

Does the code inside the if block can use item as a CountryDataItem without a need of cast and without the compiler remarking about safe calls when using the CountryDataItem The question is from the reason that the item isn't being save in any variable so i'm not sure how the compiler consider him?

2 Answers

The answer is yes. The compiler knows that if item is null then the control will never enter the if block and thus item is smart casted to CountryDataItem.

However, what you are doing is unnecessary. You should use is instead. Like so:

if (item is CountryDataItem) {
    // code that is using *item*
}

The above is only true if the field item is val. If item is a var then the compiler will not smart cast it to CountryDataItem as it may be updated elsewhere. In such a case, you will want to use a local variable. Like so:

val myItem = item 
if (myItem is CountryDataItem) {
    // code that is using *myItem*
} else {
   ...
}

or

val myItem = item as? CountryDataItem
if (myItem != null) {
    // code that is using *myItem*
} else {
    ...
}
Related