Kotlin was designed with interoperability in mind. The existing code in Java can be called from Kotlin code smoothly, but since Java has different keywords than Kotlin, we sometimes run into issues when we call Java method with a name similar to Kotlin keyword. There is a workaround in Kotlin, which allows a method to be called having a name representing a Kotlin keyword.
Escaping for Java identifiers that are keywords in Kotlin
Getting ready
Ensure that you have access to a code editor where you can write and run the code.
How to do it...
Create a Java class with a method name equal to any Kotlin keyword. I am using is as the method name, so my Java class looks as follows:
public class ASimpleJavaClass {
static void is(){
System.out.print("Nothing fancy here");
}
}
Now try calling that method from Kotlin code. If you are using any code editor with the autocomplete feature, it automatically encloses the method name in backticks (` `):
fun main(args: Array<String>) {
ASimpleJavaClass.`is`()
}
Similar is the case with other keywords in Kotlin that are qualified identifiers in Java.
How it works...
According to Kotlin’s documentation, some of the Kotlin keywords are valid identifiers in Java: in, object, is, and so on. If a Java library uses a Kotlin keyword for a method, you can still call the method, escaping it with the backtick (`) character.
The following are the keywords in Kotlin:
package | as | typealias | class | this | super | val |
var | fun | for | null | true | false | is |
in | throw | return | break | continue | object | if |
try | else | while | do | when | interface | typeof |