Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin enum implementing a Java Interface with String name() declaration

I have a Kotlin project where I make use of a Java library dependency that defines an Interface with a String name() method declaration.

In Java I'm able to use this Interfaces within enum declarations where the String name() method is implicitly implemented by the enum.

public interface Aspect {
   int index();
   String name();
}

In Java this is possible:

public enum CollisionType implements Aspect {
    ONE, TWO, THREE;

    private final Aspect aspect;
    private CollisionType() {
        aspect = CONTACT_ASPECT_GROUP.createAspect(name());
    }
    @Override
    public int index() {
        return aspect.index();
    }
}

If I try this within a Kotlin enum class, I get an [CONFLICTING INHERITED JVM DECLARATIONS] error because of the conflicting name "name". I tried to use the @JvmName annotation to define a different name as it is suggested to do by this kind of problem but I'm not able to use it properly for this problem.

enum class CollisionType : Aspect {
    ONE, TWO, TREE;
    val aspect: Aspect = CONTACT_TYPE_ASPECT_GROUP.createAspect(name())

    override fun index(): Int = aspect.index()
    @JvmName("aspectName")
    override fun name(): String = name
}

gives an errors: "The @JvmName annotation is not applicable to this declaration"

Is there any possibility to implement/use a given Java Interface defining the String name() method within a enum class in Kotlin?

Thanks

like image 999
Andreas Avatar asked Dec 16 '17 18:12

Andreas


1 Answers

As far as I can see now best option for you is following:

interface Aspect2: Aspect {
  fun myName() = name()
}
enum class CollisionType : Aspect2 {
  ………
}

And so on

like image 110
asm0dey Avatar answered Oct 09 '22 00:10

asm0dey