Safe cast operator (as?) throws exception

Please write into the docs that it succeeds even if the type is wrong. That’s all I would like to see there, so when I focus on some task I can open the docs, read it, ignore thinking and go on with my work.

After the 5th time I won’t need to open the docs because I’ll remember.

I really don’t understand why you are so much agains writing down this detail. But I give up. I asked, not much more I can do.

Just FYI, I’m not from JetBrains if this is what you mean :slight_smile: Maybe someone from JB will answer here. Or you can create a PR with your suggested improvement: kotlin-web-site/docs/topics/typecasts.md at master · JetBrains/kotlin-web-site · GitHub

The PR is a good idea, I’ll do that. Thx.

But those are (subsets of) the same reason: the value isn’t valid for the type.

Remember that nullability is built into Kotlin’s type system, so it doesn’t need to handle nulls specially. If a type is nullable, that means that null is a valid value of that type, and so as? will succeed in casting it (in the same way as a non-null instance of the type). Whereas if the type is non-nullable, then null is not a valid value, and so casting it will fail (in the same way as a non-null instance of an incompatible type).

So as? either succeeds in casting the value, or it fails. In the case of null, that will depend on whether it’s being cast to a nullable or a non-nullable type; just as in the case of an Int value, that’ll depend on whether it’s being cast to Int or a supertype.

The only thing that’s special about null here is that it’s the result of using the as? operator on an incompatible value. But don’t confuse that with its arguments.

2 Likes

The saddest thing that it also happens in the KMP common code (when you build JVM target), common code should not depend on the platform. The common code should no longer know anything about JVM. At the end we will have to put if condition in common code, depending on the platform.

What do you mean exactly? This code is an incorrect Kotlin code, no matter the target platform. It may behave differently on different platforms, maybe even perform a checked cast on some of them (? I doubt it), but still, we shouldn’t use this code.

1 Like