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

前端 未结 1 1493
闹比i
闹比i 2020-12-14 01:34

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

相关标签:
1条回答
  • 2020-12-14 02:01

    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

    0 讨论(0)
提交回复
热议问题