斯卡拉(Scala):如何在字面上避免反引号?

编程入门 行业动态 更新时间:2024-10-28 05:19:03
本文介绍了斯卡拉(Scala):如何在字面上避免反引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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):如何在字面上避免反引号?

本文发布于:2023-11-23 11:04:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:引号   字面   斯卡   如何在   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!