需要澄清 Scala 文字标识符(反引号) [英] Need clarification on Scala literal identifiers (backticks)

查看:40
本文介绍了需要澄清 Scala 文字标识符(反引号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 Scala 编程第 2 版后发现:

Reading the Programming in Scala 2nd Ed and I came across this:

文字标识符这个想法是你可以把运行时接受的任何字符串作为反引号之间的标识符"

literal identifier "The idea is that you can put any string that's accepted by the runtime as an identifier between backtick"

我不完全确定为什么要使用它?书中给出了一个在Java的Thread类中访问静态yield方法的用例.

I'm not entirely sure why I would use this? The book gave a use case of accessing the static yield method in Java's Thread class.

所以因为在 Scala 中,yield 是一个保留字,如果我使用带反引号的 yield,

So since in Scala, yield is a reserve word, if I use yield with backticks,

Thread.`yield`()

它会忽略 Scala 的 yield 并让我访问 Java 的 Thread 类的方法 yield 吗?

it would ignore the Scala's yield and let me access the Java's Thread class's method yield instead?

提前致谢.

推荐答案

正是如此.使用反引号,您可以或多或少地为字段标识符命名.事实上,你甚至可以说

Exactly. Using backticks, you can more or less give any name to a field identifier. In fact, you can even say

val ` ` = 0

它定义了一个名为(一个空格字符)的变量.

which defines a variable with name (one character of whitespace).

标识符的字面定义在两种情况下很有用.第一种情况是,当 Scala 中已经有一个同名的保留字,而您需要使用一个不关心它的 Java 库(当然,为什么要这样做).

The literal definition of identifiers is useful in two cases. The first case is, when there is already a reserved word of the same name in Scala and you need to use a Java library which does not care about that (and of course, why should it).

另一个用例带有 case 语句.约定是小写名称是指匹配变量,而大写名称是指来自外部作用域的标识符.所以,

The other use case comes with case statements. The convention is that lower case names refer to match variables, whereas upper case names refer to identifiers from the outer scope. So,

val A = "a"
val b = "b"
"a" match {
  case b => println("b")
  case A => println("A")
}

打印 "b" (如果编译器足够笨,不会因为 case A 无法访问而失败).如果要引用原先定义的val b,则需要使用反引号作为标记.

prints "b" (if the compiler were dumb enough not to fail with saying case A were unreachable). If you want to refer to the originally defined val b, you need to use backticks as a marker.

"a" match {
  case `b` => println("b")
  case A => println("A")
}

打印"A".

添加在这个最近的问题中有一个更高级的用例带尖括号 (<>) 的方法 需要反引号来让编译器消化 setter 方法的代码(它本身使用一些魔法"语法).

Add There is a more advanced use case in this recent question method with angle brackets (<>) where the backticks were needed to get the compiler to digesting the code for a setter method (which in itself uses some ‘magic’ syntax).

这篇关于需要澄清 Scala 文字标识符(反引号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆