kotlin safe/unsafe cast (redundant question mark?)

Viewed 154

I read the Kotlin lang docs and it addresses both of these cases:

Unsafe cast:

val x: String = y as String

Safe cast:

val x: String? = y as? String

but Kotlin seems to allow this as well (note the right most ?:

val x: String? = y as? String?

Is the furthest most ? redundant in this case?

2 Answers

Simply put yes. The reason being that as? is a nullable cast operator, meaning that if in your example y is null then the cast is not even tried (effectively, as you wrote, performing a safe cast). Only when y is not null, the cast is performed and therefore having String or String? has exactly the same effect, actually making ? redundant in this case.

Agreed with João Dias answer, the ? in String? is redundant, you can check also the code behind by decompile the kotlin bytecode. Both as? String and as? String? produce the same compiled code as follows

String var10001 = this.y;
if (!(var10001 instanceof String)) {
   var10001 = null;
}

this.x = var10001;
Related