7

I've got some classes defined in java, similar to the code below. I'm trying to access SomeValue through a derived java class, which is allowed in java, but not in kotlin.

Is there a way to access the field through the derived class?

// java file
// -------------------------------------------------

class MyBaseClass {
    public static final class MyInnerClass
    {
        public static int SomeValue = 42;
    }
}

final class MyDerivedClass extends MyBaseClass {
}

// kotlin file
// -------------------------------------------------

val baseAccess = MyBaseClass.MyInnerClass.SomeValue;
// this compiles

val derivedAccess = MyDerivedClass.MyInnerClass.SomeValue;
//                                 ^ compile error: Unresolved reference: MyInnerClass

keccs
  • 153
  • 1
  • 6
  • 1
    Huh. Works in Java, though that doesn't help you. :-) – T.J. Crowder Apr 30 '19 at 09:03
  • 2
    Just out of curiosity, why would you do that? I see no real use case where this would be appropriate – Lino Apr 30 '19 at 09:03
  • My database schemas are stored in classes named Schema_V1 to Schema_V42, with static members that store information about the tables/columns. There is also a derived Schema_Latest class, that extends the latest schema. This Schema_Latest is basically just a type alias for the latest schema, which is the one used everywhere, except in the code that does database schema upgrades. I'm trying to reference Schema_Latest.MyTable.SomeColumn in a query, in kotlin code. – keccs Apr 30 '19 at 10:40

1 Answers1

4

In Kotlin, nested types and companion objects are not automatically inherited.

This behavior is not specific to Java, you can reproduce the same behavior in Kotlin alone:

open class Base {
    class Nested
}

class Derived : Base()

val base = Base.Nested::class        // OK
val derived = Derived.Nested::class  // Error: 'Nested' unresolved

As such, you explicitly have to qualify the nested class using the base class.

This behavior was deliberately made more strict in Kotlin, to avoid some of the confusion in Java related to accessing static members/classes via derived types. You also see that a lot of IDEs warn you in Java when you use a derived class name to refer to static symbols in the base class.

Regarding terminology, Kotlin has a clear definition of inner classes (namely those annotated with the inner keyword). Not all nested classes are inner classes. See also here.

Related:

TheOperator
  • 5,936
  • 29
  • 42