How to access an object with creative names in scala?

For example, given

object ~ {
   def foo = ???
}

How do I access this method?

None of them work:

~.foo  

`~`.foo

With the compiler complains "illegal start of a simple expression."

And yes, I know that I probably shouldn't call the classes “~”, but both the standard library and some other libraries, and sometimes you need to work with them.

Added: Looking at sschaef answer , I tried

 $tilde.foo

And it really works. Not sure if this is intended or just a detailed implementation of how these names translate into JVM identifiers. And will this work in other scala variants (e.g. Scala.js)?

I will leave it open to see, maybe someone is calling with a more extensive answer.

+4
1

, , 2.11:

Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_102).
Type in expressions for evaluation. Or try :help.
scala> object ~ { def foo = 0 }
defined object $tilde

scala> ~.foo
<console>:1: error: illegal start of simple expression
~.foo
 ^

2.12 :

Welcome to Scala 2.12.0 (OpenJDK 64-Bit Server VM, Java 1.8.0_102).
Type in expressions for evaluation. Or try :help.
> object ~ { def foo = 0 }
defined object $tilde
> ~.foo
res0: Int = 0
+5

Source: https://habr.com/ru/post/1660390/


All Articles