Search code examples
scalapattern-matchingsyntactic-sugarbackticks

Scala - Can Match-extraction be used on backtick identifiers?


The question is a little difficult to phrase so I'll try to provide an example instead:

def myThing(): (String, String, String) = ("", "", "")

// Illegal, this is a Match
val (`r-1`, `r-2`, `r-3`) = myThing()

// Legal
val `r-1` = myThing()._1

The first evaluation is invalid because this is technically a match expression, and in a match backtick marked identifiers are assumed to be references to an existing val in scope.

Outside of a match though, I could freely define "r-1".

Is there a way to perform match extraction using complex variable names?


Solution

  • You can write out the full variable names explicitly:

    def myThing(): (String, String, String) = ("a", "b", "c")
    
    // legal, syntactic backtick-sugar replaced by explicit variable names
    val (r$minus1, r$minus2, r$minus3) = myThing()
    
    println(`r-1`, `r-2`, `r-3`)
    

    But since variable names can be chosen freely (unlike method in Java APIs that are called yield etc.), I would suggest to invent simpler variable names, the r$minusx-things really don't look pretty.