Scala: How to escape a backtick in a literal?

点点圈 提交于 2019-12-23 09:05:06

问题


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]

回答1:


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"
                      ^


来源:https://stackoverflow.com/questions/55539996/scala-how-to-escape-a-backtick-in-a-literal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!