Reputation: 718
Custom annotation is defined below:
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Custom(val a: String,
val b: String = "[null]",
val c: String = "[null]")
Desired usage:
1.
@Custom(a = "Testa", b = "Testb", c = "Testc")
fun xyz(){ ... }
2.
@Custom(a = "Testa")
fun pqr(){ ... }
When I am trying desired usage #2, it throws No values passed for parameter "b"
.
How can it be achieved to have optional parameters in kotlin cusotm annotations?
Upvotes: 1
Views: 3257
Reputation: 170713
Your code works as is, which can be verified by
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Custom(val a: String,
val b: String = "[null]",
val c: String = "[null]")
object W {
@Custom(a = "Testa")
fun pqr(){}
}
fun main(args: Array<String>) {
println(W::class.java.getMethod("pqr").getAnnotations()[0])
}
printing @Custom(b=[null], c=[null], a=Testa)
, so b
and c
got their default values. (You could also write W::pqr.annotations[0]
, but that doesn't work on the playground.)
Upvotes: 2