Scala FAQ: Can you use a question mark to end a method name?

Scala FAQ: Can you use a question mark to end a Scala method name?

Answer: Yes, you can. Just use an underscore character before the question mark. For instance, here’s a method named alive_?:

def alive_? = true

Another possible approach you can use is to use backtick characters around the method name, without using an underscore:

def `alive?` = true

However, I don’t care for that approach, because you then have to use the backticks when calling the method name.

Examples

This is what happens in the Scala REPL if you try to use a ? character at the end of a method name without using an underscore:

scala> def equal? (a: Int, b: Int): Boolean = { a == b }
<console>:1: error: '=' expected but identifier found.
def equal? (a: Int, b: Int): Boolean = { a == b }
         ^

Clearly that doesn’t work. But when you add an underscore before the question mark you’ll see that you can create and use the method:

scala> def equal_? (a: Int, b: Int): Boolean = { a == b }
equal_$qmark: (a: Int, b: Int)Boolean

scala> equal_?(1,1)
res3: Boolean = true

scala> equal_?(1,2)
res4: Boolean = false

Here’s what the backticks approach looks like:

# define the method
scala> def `equal?` (a: Int, b: Int): Boolean = { a == b }
equal$qmark: (a: Int, b: Int)Boolean

# try using it without backticks
scala> equal?(1,1)
<console>:12: error: not found: value equal
       equal?(1,1)
       ^

# use it with the backticks
scala> `equal?`(1,1)
res6: Boolean = true

Discussion

Using a question mark character at the end of a method name is something I first saw in Ruby. Some people like to use it on method names when a method returns a boolean value.