官术网_书友最值得收藏!

AnyVal

The latter, AnyVal, represents values not implemented as objects in the underlying runtime system. Scala has some predefined numeric and non-numeric value classes as shown in the class hierarchy.

It's possible to define user-defined value types as well, with some conditions applied. Remember I asked you to take a closer look at the source of the Int.scala file? You may have noticed that there are no val  or var declarations in the class Int that extends AnyVal. This is one of the constraints of defining a subtype of AnyVal. One of the reasons you might consider defining an AnyVal type is to avoid object instantiation at runtime. Some of the constraints are:

  • It must have a single val parameter that is the underlying representation. It means that if you declare class Num(val underlying: Int) extends AnyVal, then the compile time representation of it will be of type Num, but at runtime it'll be converted to Int, and methods defined within will be used as statics.
  • It must define only def, no val, var, nested classes, traits, or objects.
  • It can only extend universal traits, traits that extend only the super type Any.
  • It can't be used for pattern-matching, or type tests.

Scala's implementation of AnyVal includes nine implementations. Out of them, Byte, Short, Int, Long, Char, Float, and Double are numeric value types, while Boolean and Unit are non-numeric types.

主站蜘蛛池模板: 巴林左旗| 大丰市| 莲花县| 道孚县| 崇明县| 西贡区| 张北县| 舞阳县| 清丰县| 永寿县| 房山区| 麻江县| 长垣县| 花莲市| 全椒县| 遂宁市| 吉木乃县| 高唐县| 晋宁县| 西和县| 平山县| 石台县| 庆城县| 抚宁县| 隆尧县| 嘉禾县| 隆德县| 和政县| 措勤县| 榕江县| 新龙县| 马山县| 临洮县| 防城港市| 邵东县| 松阳县| 望都县| 鹤山市| 于都县| 三门县| 宁化县|