According to the documentation, if your Java identifier is a keyword in Kotlin, you can still use it in Kotlin if you wrap it in backticks.
For example, if you have this in Java:
public class JavaClass {
public static int val = 3;
}
You can access it in Kotlin this way:
fun main(args: Array<String>) {
println(JavaClass.`val`) // prints 3
}
EDIT (v2):
What about reverse from kotlin to java here java is strictly typed lang,how it consider kotlin val keyword
If your Kotlin identifier is a Java keyword, then you may have trouble.
For methods, the @JvmName("other-name")
annotation can be used in Kotlin to override the method name.
Kotlin:
class KotlinClass {
@JvmName("otherName")
fun new() {
// ...
}
}
Java:
public static void main(String[] args) {
KotlinClass.otherName();
}
But for fields, AFAIK there's no solution provided by Kotlin or Java.
It's better not to use Kotlin keywords, nor Java keywords in your programs.
EDIT (v1): (misunderstood the second question, and wrote in general about how to use Kotlin fields in Java)
Kotlin properties will be seen as getter and setter methods in Java. Properties declared with val
will only have a getter. If you add @JvmField
to a Kotlin property, you can then access that field also in a direct way. (val
will be final, as expected).
Kotlin:
class KotlinClass {
val a = 1
var b = 2
@JvmField val c = 3
@JvmField var d = 4
}
Java:
public static void main(String[] args) {
KotlinClass o = new KotlinClass();
o.getA(); // 1
// o.setA(1); // not exists
o.getB(); // 2
o.setB(1);
o.c; // 3
o.getC(); // 3
// o.c = 1; // compile error
// o.setC(1); // not exists
o.d; // 4
o.getD(); // 4
o.d; = 4
o.setD(1);
}