Sangmin Lee
05/05/2021, 7:48 AMvar metadata = field.getAnnotation(AnnotationA::class.java) ?: field.getAnnotation(AnnotationB::class.java)
if (metadata != null) {
someFunction(metadata) // which has two overrided functions with AnnotationA and AnnotationB
}
Compiler says “None of the following functions can be called with the arguments supplied.”
and it says metadata is casted to ‘Annotation!’
How can I set metadata AnnotationA or AnnotationB, and use my overrided function according to the type?Tobias Berger
05/05/2021, 8:00 AMvar metadata = field.getAnnotation(AnnotationA::class.java) ?: field.getAnnotation(AnnotationB::class.java)
when (metadata) {
is AnnotationA -> someFunction(metadata)
is AnnotationB -> someFunction(metadata)
else -> {} // do nothing (this is not required, only avoids potetial compiler warning for non-exhaustive when)
}
2:
field.getAnnotation(AnnotationA::class.java)?.let { someFunction(it) }
?: field.getAnnotation(AnnotationB::class.java)?.let { someFunction(it) }
I prefer version 2, but depending on the case maybe return inside let
instead of using ?:
Sangmin Lee
05/05/2021, 8:06 AM