Literals in Scala allow to define identifier as this answer describes. Is there a way though to escape a backtick ` within a literal? To do something like:
val `hello `world` = "hello world"
Update:
One of the use case for this is to use the refined library for some refined types that matches a regex containing a backtick, for instance:
import eu.timepit.refined._
import eu.timepit.refined.api.Refined
type MatchesRegexWithBacktick = String Refined MatchesRegex[W.`(a|`)`.T]
It can't be done with the Scala compiler as-is, but maybe it would be possible with a compiler plugin that changed the way identifiers were parsed (perhaps if the back-tick's function was somehow replaced with some obscure unicode character).
In the Scala SLS 1.1, there is the lexical syntax for identifiers:
op ::= opchar {opchar}
varid ::= lower idrest
boundvarid ::= varid
| ‘`’ varid ‘`’
plainid ::= upper idrest
| varid
| op
id ::= plainid
| ‘`’ { charNoBackQuoteOrNewline | UnicodeEscape | charEscapeSeq } ‘`’
idrest ::= {letter | digit} [‘_’ op]
The problem is, the only rule that allows any character other than letters, digits, or _
is the one that requires the identifier be quoted with back-ticks:
‘`’ { charNoBackQuoteOrNewline | UnicodeEscape | charEscapeSeq } ‘`’
However, it explicitly doesn't allow back-ticks with charNoBackQuoteOrNewline
, and in case you think you can work around it with UnicodeEscape
, that doesn't work either:
scala> val `hello \u0060world` = "hello world"
<console>:1: error: unclosed quoted identifier
val `hello \u0060world` = "hello world"
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With