https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Sangmin Lee

05/05/2021, 7:48 AM
Hi, I’m from python and newbie to kotlin/java. I’m wondering how to assign different annotation to variable and call function with it.
Copy code
var 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?
t

Tobias Berger

05/05/2021, 8:00 AM
you will need to restructure your code or add type checks and call the corresponding function for each case (should be no problem due to smart casting). Function overloads are resolved at compile time, not runtime. The compiler needs to know which function to call which is not possible in your example. I suggest one of these approaches: 1:
Copy code
var 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:
Copy code
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
?:
🙌 1
s

Sangmin Lee

05/05/2021, 8:06 AM
Thanks for the concrete example code, Tobias!
Now I got that in java/kotlin I need to explicitly call function for each type, which was confusing me. Thanks!! 🙂
2 Views