https://kotlinlang.org logo
#random
Title
# random
e

elye

10/24/2019, 2:27 AM
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

bodiam

10/24/2019, 5:51 AM
"Not working" ... means? Do you get an error? What is 'instantiating an annotation class' ?
e

elye

10/24/2019, 11:16 AM
MyKey
is final, and can’t be instantiated.
e

Evan R.

10/24/2019, 1:03 PM
Try making your annotation class an open class. Classes in kotlin cannot be inherited from by default and need to be marked “open”
k

karelpeeters

10/24/2019, 1:31 PM
And annotation classes can't be open: https://youtrack.jetbrains.com/issue/KT-22265
e

Evan R.

10/24/2019, 1:42 PM
Whoops, didn’t know that
c

cedric

10/24/2019, 5:23 PM
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

karelpeeters

10/24/2019, 5:30 PM
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?
2 Views