加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala选项?为什么有些人不继承AnyVal,为什么它不是值类型?

发布时间:2020-12-16 19:17:17 所属栏目:安全 来源:网络整理
导读:为什么 Scala有些不从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
为什么 Scala有些不从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.

大胆的将一些人排除在当前写成的价值等级之外.其中的第二个可能会通过稍微改变来解决,但前者会将其杀死.如果某些值本身成为值类,则无法在其中包含另一个值类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读