Search code examples
kotlinmatcher

Why does it have to be the`is` in Kotlin?


When trying to convert code from Java to Kotlin for an Espresso test,

Java code:

onData(allOf(is(instanceOf(String.class)), is("Americano")))
  .perform(click());

Kotlin code:

onData(allOf(`is`(instanceOf(String::class.java)),
    `is`("Americano"))).perform(click())

The 'is' is actually:

public static <T> Matcher<T> is(T value) {
    return Is.is(value);
}

Why does the syntax for it become 'is' in Kotlin?


Solution

  • is is a reserved keyword in Kotlin. For interoperability with Java and other programming languages that can name fields or method like reserve words in Kotlin we use backticks to escape names. For example in your case method is from Java is escaped with backticks:

    onData(allOf(`is`(instanceOf(String::class.java)),
    `is`("Americano"))).perform(click())
    

    Another example of escaping using when method of Mockito library:

    Mockito.`when`(/*some method is called*/).thenReturn(/*return some result*/)
    

    Documentation regarding Calling Java code from Kotlin:

    Some of the Kotlin keywords are valid identifiers in Java: in, object, is, etc. If a Java library uses a Kotlin keyword for a method, you can still call the method escaping it with the backtick (`) character:

    foo.`is`(bar)