2

I found following code in a book

val list = List(5, 4, 3, 2, 1)
val result = (0 /: list) { (`running total`, `next element`) ⇒
  `running total` - `next element`
}

Are backticks used to create a variable name with spaces?

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

1 Answers1

12

Using back tickets invalid variable name can be valid. You can use scala reserved key words as variable names as well when you use backticks. You can use space separated and even newline separated variables with back ticks as valid variable names.

Scala backticks

scala> val `hello world` = "asdjaklsdja"
hello world: String = asdjaklsdja

scala> val `val` = "fasfasadsas"
val: String = fasfasadsas

scala> val `class` = "fasfasadsas"
class: String = fasfasadsas

scala> val `case` = "fasfasadsas"
case: String = fasfasadsas

scala> val `foo bar \n foo bar` = "asdasdasd"
foo bar
 foo bar: String = asdasdasd

Backticks in Pattern matching

scala> val age = 18
age: Int = 18

scala> :paste
// Entering paste mode (ctrl-D to finish)

def is18(a: Int): Boolean = a match {
 case `age` => true
 case _ => false
}

// Exiting paste mode, now interpreting.

is18: (a: Int)Boolean

scala> is18(21)
res0: Boolean = false

scala> is18(18)
res1: Boolean = true

In pattern matching, it helps you to use variable as if its a concreate value.

Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40