gpt4 book ai didi

斯卡拉选项?为什么 Some 不继承 AnyVal ,为什么它不是值类型?

转载 作者:行者123 更新时间:2023-12-04 12:08:03 26 4
gpt4 key购买 nike

为什么Scala Some不继承AnyVal,使用值类型特性,节省装箱成本?

就像是:

sealed trait TestOption[+A] extends Any {
def isEmpty: Boolean
def get: A
}

final case class TestSome[+A](val x: A) extends AnyVal with TestOption[A] {
def isEmpty = false
def get = x
}

case object TestNone extends TestOption[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}

最佳答案

来自 Value Classes 的文档:

Summary of Limitations

A value class

  • must have only a primary constructor with exactly one public, val parameter whose type is not a value class. (From Scala 2.11.0, the parameter may be non-public.)
  • may not have specialized type parameters.
  • may not have nested or local classes, traits, or objects
  • may not define a equals or hashCode method.
  • must be a top-level class or a member of a statically accessible object
  • can only have defs as members. In particular, it cannot have lazy vals, vars, or vals as members.
  • cannot be extended by another class.


粗体不包括 Some从作为当前编写的值类。其中的第二个可能可以通过轻微的更改来解决,但前者会杀死它。您将无法在 Some 中包装另一个值类如果 Some 本身成为一个值类。

关于斯卡拉选项?为什么 Some 不继承 AnyVal ,为什么它不是值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23433673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com