Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Scala in Java: weird classes & methods showing

Tags:

java

scala

I recently started learning Scala, and tried to use my Scala code in Java. The imported jar files work and include my classes and methods; however, i was a bit surprised when i found that, among the available classes for importing, i could access both DiceRoller and DiceRoller$, and that I also could reach methods such as attribute_$eq in a normal class.

DiceRoller is defined as object in Scala, and the rest of classes are defined as class, if that may shed some light into the matter.

I also know the basic theory on anonymous classes and functions, and how Scala considers operations such as "==" functions, so that's not my point, even though it can be related.

When I import Java packages, those classes and methods are unreachable. So, why can I call them when I'm importing Scala jar files? Can I declare those anonymous classes and methods as private?

like image 406
DSalas Avatar asked Jun 07 '15 11:06

DSalas


1 Answers

The JVM doesn't know anything about Scala. The Scala compiler has to map Scala constructs to JVM constructs in some way.

For example, the JVM doesn't have objects, so the Scala compiler maps objects to classes with a singleton instance.

The JVM doesn't have traits either, so those have to be mapped to classes. (Actually, the mapping of traits is fairly complex, in fact, traits get mapped to multiple classes.)

In Scala, fields can be overridden by methods, in the JVM, they can't. Therefore, Scala fields have to be mapped to something which can be overridden by methods, which is methods.

Note also, that your Java IDE knows nothing about how Scala encodes Scala constructs as JVM constructs. For example, the JVM doesn't know anything about anonymous classes, so the Java compiler encodes anonymous classes as regular named classes with strange names. The Java IDEs know about those strange names and don't show them, but the Java IDEs don't know about the names the Scala compiler uses.

The JVM doesn't know anything about functions. Now, Java 8 has first-class functions, and there is a standardized encoding for them that Java IDEs understand, but Scala had first-class functions before Java had them, and the encoding they came up with is different from the one the Java designers came up with. (This is going to change in the next versions of Scala, though.)

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

like image 126
Jörg W Mittag Avatar answered Nov 14 '22 15:11

Jörg W Mittag