Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to understand "final abstract class Int private extends AnyVal in Scala

Tags:

scala

Coming from Java Land I have been trying to teach myself Scala. Recently I was toying with the Int data type and I decided to look up the API for the Int class here.

What perplexed me was the class definition for Int, which is abstract final.

I am apologetic if I did not read up on the meaning of abstract and final in Scala before asking this question, but I was curious, so I typed out this post right away.

So what I am trying to understand is: Are the semantics for abstract, final and extends different in Scala? Again, it is to the best of my understanding that in Java, one cannot have abstract and final at the same time. So how do I interpret final abstract class Int private extends AnyVal?

like image 213
ilango Avatar asked Sep 05 '12 21:09

ilango


1 Answers

As om-nom-nom pointed out in the comment, abstract forbids instantiation (new Int), whereas final forbids subclassing (new Int { ... }).

The reason for this is that scala.Int is directly represented by the primitive integer type of the Java virtual machine; the other similar types are Byte, Short, Char, Long, Float, Double, Boolean. Because they are primitive types on the runtime (exhibiting better performance than so-called boxed types) and the JVM does not allow to add new primitives, there would be no legal way to extend those types. Also there is no way to instantiate them other than by giving a literal (val i: Int = 33).

Scala has these types to create a unified object system where there is no logical difference between primitive types and 'objects'. There is however a hierarchical distinction at the top which is AnyRef (corresponding to java.lang.Object) and AnyVal (corresponding to those primitive types; and adding Scala's new type Unit).

More on the unified type system is given by the Tour of Scala: Unified Types

like image 169
0__ Avatar answered Oct 07 '22 11:10

0__