2 Nov 2011

Backticks in Scala

I am still trying to overcome my distaste towards JVM based languages, but Scala makes an intriguing study. And, it has certainly grown on me over the past month.

Anyway, I thought it’s worth mentioning the use of backticks (``) in Scala. Scala allows you to define identifiers that start and end with backticks and can contain pretty much anything between them, including spaces! Which means, `start date` is a valid identifier. So is, `yeah you get the point`.

This is handy, because it allows you to define methods as readable as:

def `Given I login as user`(username:String) = {
    // do something with username
}

This is perfect for writing Cucumber-like automated tests. You can describe behavior directly using Scala methods, instead of resorting to plain text. Of course, it’s definitely more restrictive, but one clear advantage is the ability to use the refactoring tools available in your IDE. Using find and replace to edit plain text behavior descriptions can be painful.

Backticks also come in handy in a couple of other places. If you happen to use a Java library whose method name is actually a reserved keyword in Scala (say, val), you should surround the keyword with backticks! So, you can happily say:

foo.`val`();  // it works!

Similarly, you can use backticks in match statements to match variables beginning with lower case letters (match binds identifiers starting with a lower case letter with the pattern matched, while identifiers starting with an upper case letter is treated as identifiers from the outer scope). So,

val Foo = "foo"
val foo = "bar"
 
"foo" matches {
    case foo => println("bar")
    case Foo => println("foo")
}

would actually print bar. To refer to the value of the foo variable, you should backticks like this:

val Foo = "foo"
val foo = "bar"
 
"foo" matches {
    case `foo` => println("bar")
    case Foo => println("foo")
}
 
// prints "foo" correctly
Tagged with:

Leave a Reply