91

What are the backticks used for in the snippet below?

Why add them around the fun is(amount:Int ):Boolean { ... }?

verifier.`is`(amount)
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
LF00
  • 27,015
  • 29
  • 156
  • 295

6 Answers6

126

It's because is is a reserved keyword in Kotlin. Since Kotlin is supposed to be interoperable with Java and is is a valid method (identifier) name in Java, the backticks are used to escape the method so that it can be used as a method without confusing it as a keyword. Without it it will not work because it would be invalid syntax.

This is highlighted in the Kotlin documentation:

Escaping for Java identifiers that are keywords in 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)
Community
  • 1
  • 1
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • 3
    I'd also like to add that "in the wild", this is often used to have _identifier names with spaces_ in them, [example](https://stackoverflow.com/a/58955270/771032). – MrCC Nov 24 '20 at 06:05
23

Useful for tests

Backticks are very useful in tests for long function names:

@Test
fun `adding 3 and 4 should be equal to 7`() {
    assertEquals(calculator.add(3, 4), 7)
}

This makes the function names more readable. We can add spaces and other special characters in the function names. However, remember to use it only in tests, it's against the Kotlin coding conventions of the regular code.

Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105
12

It allows you to call a Java method whose name is a Kotlin keyword. It won't work if you leave out the backticks.

wero
  • 32,544
  • 3
  • 59
  • 84
11

The backtick are a "workaround" to allow you to call methods that have a name representing a Kotlin keyword.

See kotlinlang:

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

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

is in list of Kotlin reserved words To use Kotlin reserved word (such as is or object) for function/class name you should wrap it to backticks

Lorin Hochstein
  • 57,372
  • 31
  • 105
  • 141
gildor
  • 1,789
  • 14
  • 19
1

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

https://kotlinlang.org/docs/reference/java-interop.html

Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19