Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

trying to understand "final abstract class Int private extends AnyVal in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...