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

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.

主站蜘蛛池模板: 扎兰屯市| 镇坪县| 萍乡市| 治县。| 东源县| 珠海市| 金寨县| 新沂市| 西乌| 定兴县| 灵川县| 哈巴河县| 侯马市| 阳西县| 周至县| 湘潭县| 通河县| 彩票| 高唐县| 湛江市| 渭源县| 休宁县| 桂平市| 安溪县| 开江县| 孟村| 措勤县| 中超| 景谷| 错那县| 五台县| 水富县| 安平县| 漳州市| 鸡东县| 广州市| 牡丹江市| 启东市| 黄浦区| 楚雄市| 临桂县|