Sumit T
Sumit T

Reputation: 1363

Kotlin public constant is not accessible in other Java class?

In my Kotlin class A, I have a public constant defined, like:

class A {
    companion object {
        val TESTVALUE = "MY TEST VALUE"
    }
    ....
}

And in my other Java class B, I am trying to use it, like:

class B {

    private void testFunction() {
        String testValue = A.Companion.TESTVALUE
        // 'or'
        String testValue = A.TESTVALUE

        .....
    }
    ....
}

The error that I get is: 'TESTVALUE has private access'

enter image description here

Upvotes: 3

Views: 1502

Answers (4)

android iPhone
android iPhone

Reputation: 880

If you cannot modify the Kotlin class (e.g. it's an auto-generated file) it should be ok retrieve a field by adding get the variable name.

A.kt

    public class DateTime {
      public companion object {
        public val type: CustomScalarType = CustomScalarType("DateTime", "java.util.Date")
      }
    }

B.java

    private void testFunction() {
        String testValue = DateTime.Companion.getType();
    }

Upvotes: 0

0xA
0xA

Reputation: 1540

JvmField. Instructs the Kotlin compiler not to generate getters/setters for this property and expose it as a field. See the Kotlin language documentation for more information.

make sure you also reference fields created from a non-static context.

A.java

 class A {

    private void testFunction() {
        String testValue = B.TESTVALUE;
        System.out.println(testValue);
    }
};

B.kt

 class B {
     companion object {
         @kotlin.jvm.JvmField

         val TESTVALUE = "MY TEST VALUE"
     } }

Upvotes: 2

Vinicius Almada
Vinicius Almada

Reputation: 394

To access companion object fields from Kotlin class in Java class, you need to provide an annotation to Java reads appropriately. This annotation is @JvmField.

As shown in Kotlin docs here

class A {
   companion object {
      @JvmField
      val TESTVALUE = "MY TEST VALUE"
   }
}

Upvotes: 5

Related Questions