Java Scala import: weird classes and methods showing

I recently started to learn Scala and tried to use my Scala code in Java. Imported jar files work and include my classes and methods; however, I was a bit surprised when I discovered that among the available classes for import, I can access both DiceRoller and DiceRoller $ , and that I could also use methods like attribute_ $ eq in a normal class.

DiceRoller is defined as an object in Scala, and the rest of the classes are defined as a class if this can shed light on this question.

I also know the basic theory of anonymous classes and functions, and how Scala views operations such as "==" functions, so this is not my point, even if it might be related.

When I import Java packages, these classes and methods are not available. So why can I call them when I import Scala jar files? Can I declare these anonymous classes and methods private?

+5
source share
1 answer

The JVM does not know anything about Scala. The Scala compiler must somehow map the Scala constructs to the JVM constructs.

For example, the JVM has no objects, so the Scala compiler maps objects to classes with a singleton instance.

The JVM also has no traits, so they must be mapped to classes. (Actually, displaying traits is rather complicated; in fact, traits are mapped to several classes.)

In Scala, fields can be overridden by methods; in the JVM, they cannot. Therefore, Scala fields must be mapped to something that can be overridden by methods that are methods.

Note also that your Java IDE does not know anything about how Scala encodes the Scala construct as JVM constructors. For example, the JVM knows nothing about anonymous classes, so the Java compiler encodes anonymous classes as ordinary named classes with strange names. The Java IDEs are not aware of these strange names and do not show them, but the Java IDEs are not aware of the names that the Scala compiler uses.

The JVM knows nothing about functions. Now Java 8 has first-class features, and there is a standardized encoding for them that the Java IDE understands, but Scala has first-class functions before they had Java, and the encoding they came up with is different from what the Java developers came up with. (However, this will change in future versions of Scala.)

Note that the same thing happens with Clojure, Groovy, Python, Ruby, JavaScript, Fantom, Kotlin, and all other JVM languages. Java tools just don't know about them.

+9
source

All Articles