From the course: Writing Secure Code for Android by Infosec

Unlock this course with a free trial

Join today to access over 24,900 courses taught by industry experts.

Null safety, part 5: Safe cast and unsafe cast operators

Null safety, part 5: Safe cast and unsafe cast operators

From the course: Writing Secure Code for Android by Infosec

Null safety, part 5: Safe cast and unsafe cast operators

- Null safety, part five. Safe cast, unsafe cast operators. Further down the road of null safety. Are we there yet? (chuckles) There's a lot to null safety, right? And I know it can be confusing at first. Let's talk now about the safe cast and the unsafe cast operators. You could safely cast using as? For example, I have something x, its String, possibly nullable, equals y, and then safely cast it to string. If we don't do the, as we might blow up, it might be incompatible. Now, let's see this example here. This safe cast operator, it will return a null instead of blowing up on us, instead of us getting a ClassCastException. If we cannot cast, if it's not possible, it'll just give us a null. So it's a way of safely trying to cast, even though we can't really do it. Even though the right-hand side of as? is a non-null type of string, the result of the cast is still nullable. Let's take a look at this example here. We've got an object of type Any, and we're assigning it 123. That's an…

Contents