Say I have `annotation class RunCount(val count: ...
# multiplatform
j
Say I have
annotation class RunCount(val count: Int)
open class Testable
...and...
Copy code
@RunCount(3)
class TestA: Testable { ... }
With an instance, like:
val testA = TestA()
how can I figure out which annotations it has? For example, I tried this:
if (testA is RunCount) ...
But that doesn’t work. Any ideas?
d
Make
RunCount
an interface?
j
I could do that, but I was hoping to use annotations because I have about 20 of them (some of which take values), and they are more ergonomic to apply to test data classes than adding conformance to a bunch of interfaces
d
You can use delegation.
j
Can you elaborate?
d
Something like
Copy code
interface RunCount {
    val count: Int
}
class RunCountImpl(override val count: Int)

class TestA : Testable, RunCount by RunCountImpl(3) {
}
j
I see. I’d still rather use annotations if it’s possible to check which annotations are applied to an instance of a class.
I know I can get an array of annotations using reflection on the type
Is it not possible to get the same thing on an instance of a type?
d
With Java you could use reflection but in multiplatform you can do some hacks with
kotlinx.serialization
but I wouldn't recommend it.
j
How are annotations intended to be used in Kotlin if not like this then?
d
Kotlin Multiplatform isn't quite there yet, waiting for Kotlin 1.4 to bring nicer support for things like this.
Although there's an annotation processor that might just suit your needs. One sec.
j
Thanks @Dominaezzz, I’ll check that out