Scala literal identifiers (backticks) on for loops

#1

Hi all,

I’m building some statistical code and I would like to use Scala literal. It makes the code very readable since the variable name will make the code very similar to the theory.

I can do

valP(X|C)= ....

but it seems that I can’t for

for {
   `P(X|C)` <- ...
}

Is it possible to use backticks on the for comprehensions?

Who can I do it?

Best Regards

#2

Hmm – looks to me like it works. See fiddle here. What errors are you getting when you try to do this? More details might be helpful.

#3

I get errors in such code:

for {
  z <- Option(6)
  `A(X|Y)` = 8 // error: not found: value A(X|Y)
} yield z

The solution is to desugar such for-comprehension to flatMaps, maps, filters, foreaches, etc

#4

Interesting. It seems to be very fragile – here’s an updated fiddle that agrees with your failure observation but succeeds in other places. It suggests a bug in for desugaring; I suspect it’s losing the backticks when it desugars to a val assignment, but not when desugaring to a flatMap or map. I’ve opened a bug report to that effect…

#5

Backticks make it into a pattern to be matched against the value, like

val x = 7

9 match {
   case `x` => "only matches the number seven"
   case x => x.toString
}
1 Like