For the More Curious: Function Names in Backticks

Kotlin includes a feature that might, at first glance, seem slightly peculiar: the ability to define or invoke a function named using spaces and other unusual characters, so long as they are surrounded using the backtick symbol, `. For example, you can define a function like this:

    fun `**~prolly not a good idea!~**`() {
        ...
    }

And you could then invoke `**~prolly not a good idea!~**` like this:

    `**~prolly not a good idea!~**`()

Why is this feature included? You should never name a function anything like `**~prolly not a good idea!~**`. (Nor with an emoji. Please backtick responsibly.) There are several valid reasons the function name backticks exist.

The first is to support Java interoperability. Kotlin includes great support for invoking methods from existing Java code within a Kotlin file. (You will tour a number of Java interoperability features in Chapter 20.) Because Kotlin and Java have different reserved keywords, words that are forbidden for use as function names, the function name backticks allow you to dodge any potential conflict when interoperability is important.

For example, imagine a Java method name from a legacy Java project, is:

    public static void is() {
        ...
    }

In Kotlin, is is a reserved keyword (the Kotlin standard library includes an is operator; it allows you to check the type of an instance, as you will see in Chapter 14). In Java, however, is is a valid method name, since no is keyword exists in the language. Because of the backtick feature, you are able to invoke a Java is method from Kotlin, like so:

    fun doStuff() {
        `is`() // Invokes the Java `is` method from Kotlin
    }

In this case the, backtick feature supports interoperating with a Java method that would otherwise be inaccessible due to its name.

The second reason for the feature is to support more expressive names of functions that are used in a testing file. For example, a function name like this:

    fun `users should be signed out when they click logout`() {
        // Do test
    }

Is more expressive and readable than this:

    fun usersShouldBeSignedOutWhenTheyClickLogout() {
        // Do test
    }

Using backticks to provide an expressive name for a test function is the exception to the “lowercase first letter, followed by camel case” naming standard for functions.