0

As "Programming in Scala: A comprehensive step-by-step Guide" states, in Scala there are not basic types values, just objects: Integers are Int instances and doubles are Double instances. I assume that these classes map to Java's Integer, Double ... classes and, therefore, are mapped as Object subclasses.

In the book, the following type hierarchy (classes as types) is presented:

enter image description here

Few pages after this graph is presented, you can read:

enter image description here

What somehow troubles me is: If Scala´s Double maps to Java's Double which is an specification of java.lang.Object and AnyRef is an alias for java.lang.Object too, should't AnyVal be a subclass of AnyRef?

EDIT

Few pages after that I read that primitive types are not mapped to Java's primitive types wrapper classes unless their "boxed" versions are required; but I am still confused since it seems to me that not all Scala's objects are java.lang.Object sublcasses instances. That is: There are classes in Scala which could be not translated in the JVM as Object subclasses.

1 Answers1

1

Java does not only have types that extend java.lang.Object (aka scala.AnyRef), but primitive types, e.g. int, double, boolean, ... In Scala you find them under scala.Any. So a scala.Int corresponds to a Java int. Not java.lang.Integer; not until boxing occurs, a mechanism on the JVM to be able to pass primitives to generic methods. Both Java and Scala do auto-boxing, that is construct a reference around a primitive type when a reference is needed.

The difference in Scala is, it doesn't treat scala.Int any different from say String, it doesn't matter whether the type corresponds to a JVM primitive or not. You can call methods on scala.Int as if it was any regular object. In the byte-code you will still have primitive types.

This is why Scala is sometimes called a true or more pure object-oriented language than Java.

0__
  • 66,707
  • 21
  • 171
  • 266
  • I knew Java had non-object primitive types in contrast with Scala. What strikes me as strange is that not all Scala classes are mapped as classes in Java. – Pablo Francisco Pérez Hidalgo Oct 12 '14 at 21:39
  • From this question's accepted answer http://stackoverflow.com/questions/2335319/what-are-the-relationships-between-any-anyval-anyref-object-and-how-do-they-m : In Scala, on the other hand, everything is an object, all objects belong to a class, and they interact through methods. The JVM bytecode generated does not reflect this, but that doesn't make them any less so, just as Java has generics, even though the bytecode doesn't have them. – Pablo Francisco Pérez Hidalgo Oct 13 '14 at 07:22