https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
j

Justin

09/29/2019, 9:12 PM
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

Dominaezzz

09/29/2019, 9:20 PM
Make
RunCount
an interface?
j

Justin

09/29/2019, 9:34 PM
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

Dominaezzz

09/29/2019, 9:35 PM
You can use delegation.
j

Justin

09/29/2019, 9:36 PM
Can you elaborate?
d

Dominaezzz

09/29/2019, 9:37 PM
Something like
Copy code
interface RunCount {
    val count: Int
}
class RunCountImpl(override val count: Int)

class TestA : Testable, RunCount by RunCountImpl(3) {
}
j

Justin

09/29/2019, 9:38 PM
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

Dominaezzz

09/29/2019, 9:39 PM
With Java you could use reflection but in multiplatform you can do some hacks with
kotlinx.serialization
but I wouldn't recommend it.
j

Justin

09/29/2019, 9:41 PM
How are annotations intended to be used in Kotlin if not like this then?
d

Dominaezzz

09/29/2019, 9:42 PM
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

Justin

09/29/2019, 9:44 PM
Thanks @Dominaezzz, I’ll check that out