Search code examples
kotlinreflectioncastingnullannotations

Difference between as? Type and as Type?


I'm having issues figuring out the difference between these two statements.

The first one makes use of the as? operator to cast the generic annotation class to XYZ

this::class.annotations.find { it is XYZ } as? XYZ ?: return

And the second one makes use of the as? operator and of the null marker

this::class.annotations.find { it is XYZ } as XYZ? ?: return

Solution

  • In the first case, you use safe casting (as?) to not-nullable type XYZ. If it is instance of XYZ, then it will just cast it to XYZ. If it is not instance of XYZ (or if it is null), then it will return null.

    In the second case, you use unsafe casting (as) to nullable type XYZ?. If it is instance of XYZ or it is null, then it will cast it to XYZ? (or return null, if it is null). If it is not instance of XYZ, it will throw an exception.