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

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.

主站蜘蛛池模板: 玛曲县| 大同市| 庐江县| 如皋市| 阿勒泰市| 江口县| 五常市| 保山市| 饶阳县| 梁山县| 会宁县| 海宁市| 中卫市| 清水河县| 丹棱县| 晋州市| 铁力市| 竹山县| 兴安县| 仲巴县| 平山县| 锦州市| 依兰县| 宕昌县| 西乌珠穆沁旗| 司法| 长治市| 滦南县| 千阳县| 赫章县| 三门峡市| 沂水县| 鸡西市| 长武县| 湘潭县| 石狮市| 内丘县| 临泽县| 元江| 西乡县| 金乡县|