Reputation: 1363
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'
Upvotes: 3
Views: 1502
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
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
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
Reputation: 895
You need the @JvmField
annotation.
Read more here:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-field/
https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields
Upvotes: 2