Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access a superclass' enum in Kotlin?

I am converting a Java Android project to Kotlin.

I am using API.AI's client, which has two AIConfiguration classes:

Superclass

package ai.api;
public class AIConfiguration implements Cloneable {
     public static enum SupportedLanguages {
         English("en"),
         //...
     }
         //...
}

Subclass

package ai.api.android;
public class AIConfiguration extends ai.api.AIConfiguration {
    public enum RecognitionEngine {
    //...
}

In my Java code, I was creating an instance of the subclass, as recommended in the api guide:

final AIConfiguration config = new AIConfiguration("TOKEN",
        AIConfiguration.SupportedLanguages.English,
        AIConfiguration.RecognitionEngine.System);

Once converted to Kotlin, it looks like this:

val config = AIConfiguration("TOKEN",
        AIConfiguration.SupportedLanguages.English,
        AIConfiguration.RecognitionEngine.System)

...which causes an Unresolved reference: SupportedLanguages.

  • I can update the reference to ai.api.AIConfiguration.SupportedLanguages.English, which compiles successfully.
  • I could import the superclass with import ai.api.AIConfiguration as SuperAIConfiguration and use SuperAIConfiguration.SupportedLanguages, but I would rather reference the enum directly on the subclass.

I don't get it: why is this reference valid in Java but not in Kotlin?

like image 992
PLNech Avatar asked Oct 29 '22 03:10

PLNech


1 Answers

The visibility rules in Kotlin are different from those in Java. Kotlin classes do not "inherit" static nested classes from supertypes, because the rules get too complicated when companion objects come into play. We are trying to keep the rules as simple as possible, and normally there's no issue accessing a nested class through a supertype name, but in your case the short names of the subclass and superclass clash. This is not typical, so you have the options you listed in the question: a fully-qualified name or a rename on import.

like image 121
Andrey Breslav Avatar answered Nov 04 '22 14:11

Andrey Breslav