斯卡拉(Scala):如何在字面上避免反引号? [英] Scala: How to escape a backtick in a literal?
问题描述
Scala中的文字允许定义此 answer 描述的标识符.有没有办法在字面量内转义反引号`?做类似的事情:
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"
更新:
一种用例是使用 refined 库针对与包含以下内容的正则表达式匹配的某些精炼类型反引号,例如:
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]
推荐答案
使用Scala编译器不能按原样完成,但是也许可以通过更改编译器插件来实现标识符的解析方式(也许如果反勾号的功能被某种晦涩的unicode字符替换了).
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).
在 Scala SLS 1.1 ,其中包含标识符的词汇语法:
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 } ‘`’
但是,它明确不允许使用charNoBackQuoteOrNewline
来回引号,并且如果您认为可以使用UnicodeEscape
来解决它,那么也将不起作用:
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"
^
这篇关于斯卡拉(Scala):如何在字面上避免反引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!