Alex Klimashevsky
Alex Klimashevsky

Reputation: 2495

What is the different between cast and safe cast operators and null

Lets say I have 2 expressions:

val x: Int? = null as Int?

and

val x: Int? = null as? Int?

What is the different between them?

Why the first one is unsafe cast?

Upvotes: 2

Views: 1091

Answers (1)

gil.fernandes
gil.fernandes

Reputation: 14641

In practical terms the unsafe cast throws an exception when the cast fails and the safe cast converts to null when the cast operation fails.

val x1: Int? = 1.0 as? Int?
println(x1)

This prints:

null

And this code here:

val x: Int? = 1.0 as Int?

throws an exception:

Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

Upvotes: 4

Related Questions