Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

Need clarification on Scala literal identifiers (backticks)

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"

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.

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

Thread.`yield`()

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

Thank you in advance.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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).

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")
}

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")
}

Which prints "A".

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...