Hi… Inability to instantiate an annotation class i...
# random
e
Hi… Inability to instantiate an annotation class in Kotlin, is this a limitation in Kotlin vs Java? e.g. In Java
Copy code
@MapKey(unwrapValue = false)
@interface MyKey {
    String name();
    Class<?> implementingClass();
    int[] thresholds();
}
I can instantiate it
Copy code
final class MyKeyImpl implements MyKey {
    private final String name;
    private final Class<?> implementingClass;
    private final int[] thresholds;
    MyKeyImpl(
            String name,
            Class<?> implementingClass,
            int[] thresholds) {
        this.name = name;
        this.implementingClass = implementingClass;
        this.thresholds = thresholds.clone();
    }
    @Override
    public Class<? extends MyKey> annotationType() { return MyKey.class; }
    @Override
    public String name() { return name; }
    @Override
    public Class<?> implementingClass() { return implementingClass; }
    @Override
    public int[] thresholds() { return thresholds.clone();}
}
If I convert it to Kotlin
Copy code
@MapKey(unwrapValue = false)
internal annotation class MyKey(val name: String, val implementingClass: KClass<*>, val thresholds: IntArray)
The below converted Kotlin code is not working.
Copy code
internal class MyKeyImpl(
    private val name: String,
    private val implementingClass: Class<*>,
    thresholds: IntArray) : MyKey {
    private val thresholds: IntArray

    init {  this.thresholds = thresholds.clone() }
    override fun annotationType(): Class<out MyKey> { return MyKey::class.java }
    override fun name(): String { return name }
    override fun implementingClass(): Class<*> {  return implementingClass }
    override fun thresholds(): IntArray { return thresholds.clone() }
}
b
"Not working" ... means? Do you get an error? What is 'instantiating an annotation class' ?
e
MyKey
is final, and can’t be instantiated.
e
Try making your annotation class an open class. Classes in kotlin cannot be inherited from by default and need to be marked “open”
k
And annotation classes can't be open: https://youtrack.jetbrains.com/issue/KT-22265
e
Whoops, didn’t know that
c
Yeah, can’t be done. For what it’s worth, I was a member of the Experts Group that published the annotation JSR, back in 2005 or so. I remember pushing for annotation classes not being final but in the end, I think security and performance concerns prevailed.
Overall, I can’t say I’ve felt much need to implement annotation classes, personally.
k
But you can implement them in Java, so they're not final? Though I'm not really sure what that even means or when that'd be useful. Or do you mean you were pushing for them to be open in Kotlin?