The Solution: Backticks

Kotlin has naming rules for functions that are very similar to Java’s naming rules for methods, with one key difference: in Kotlin, you can use backticks around a function name. Within the backticks, just about anything is valid for the function name itself. To call such a function, you use the same function name, including the backticks

So, going back to the sample at the outset, this function declaration and invocation is perfectly legal:

fun `is this syntax really necessary?`() {
  println("Well, it has its uses...")
}

`is this syntax really necessary?`()

For ordinary code, this would get tedious, particularly if you needed to call the function a lot. In the case of something like JUnit, though, you usually do not write code that calls the test functions — the test runner calls them via reflection. So the function declaration is the only place where the backticks get used. And, given the backticks, you can name the function whatever you want — including spaces and punctuation — to make it easier to read in test output.

Note, though, that support for such function names may vary by environment. Java cannot handle such function names, so any place where Java might need to work with the actual name runs the risk of encountering problems. For example, in Android app development, escaped function names with backticks work fine for unit tests but not for instrumented tests.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.