1

I have a class in Kotlin:

class AClass {
    companion object {
        const val CONST_VAL = "THIS IS A CONST VAL STRING"
        val JUST_VAL = "THIS IS A NON-CONST VAL STRING"

        fun aFunction() {}
    }
}

and a Main class in Java which is accessing companion members:

public class Main {
    public static void main(String[] args) {
        // aFunction can only be accessed by using Companion
        AClass.Companion.aFunction();
        // CONST_VAL can only be accessed from the parent class
        String constValString = AClass.CONST_VAL;
        // JUST_VAL can only be accessed with Companion
        String valString = AClass.Companion.getJUST_VAL();
    }
}

How come, in Java, both #aFunction() and JUST_VAL can only be accessed via the Companion while CONST_VAL can only be accessed via the parent class directly? Shouldn't CONST_VAL be accessed only via the Companion as well?

Slaw
  • 37,820
  • 8
  • 53
  • 80
  • While I don't know the reasoning, the behavior itself appears to be expected; it's explicitly mentioned in the [Kotlin reference](https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields). – Slaw Dec 01 '19 at 22:35
  • 1
    Well, a const val is, by definition, a compile time constant. So, in Java, a static final field. Accessing it via the property of an object would be quite strange, since the whole point is to be able to use it as a compile time constant. – JB Nizet Dec 01 '19 at 22:56
  • @JBNizet Why not have everything compiled into the enclosing Java class then? Why only compile time constants? It would make things easier on the Java side if you could just call `AClass.aFunction()` instead have having to call `AClass.Companion.aFunction()`. As it is, you have to add `@JvmStatic` to the Kotlin function for such functionality. I'm not saying it should be one way or the other, but I believe that's why the OP is confused; apparently compile time constants are treated differently than everything else and they're wondering why. – Slaw Dec 02 '19 at 02:11
  • 1
    @Slaw because the companion object is an object. It can have state, with instance methods acting on that state; we must be able to pass it as an argument; it can implement interfaces, etc. etc. – JB Nizet Dec 02 '19 at 07:15

0 Answers0