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

斯卡拉 – 特质中的懒惰断言

发布时间:2020-12-16 08:45:42 所属栏目:安全 来源:网络整理
导读:我发现我偶尔想在一个特征中写一个任意的断言,或者在我想要断言的东西尚未完全定义的其他地方. trait Foo { val aList: List[String] val anotherList: List[String] def printPairs = aList.zip(anotherList).foreach(println) assert(aList.size == anothe
我发现我偶尔想在一个特征中写一个任意的断言,或者在我想要断言的东西尚未完全定义的其他地方.

trait Foo {
  val aList: List[String]
  val anotherList: List[String]

  def printPairs = aList.zip(anotherList).foreach(println)

  assert(aList.size == anotherList.size) // NullPointerException,because these references are undefined right now.
}

我想我正在寻找的一个概括是一个钩子(总是)在完全定义和实例化类之后触发,因为这是我通常在构造函数中放置的那种检查.

解决方法

您可以使用早期定义(在 Scala Language Reference中搜索更多信息)来实现它 – 与您编写的特征完全相同,您可以按如下方式扩展它:

class Bar(l1: List[String],l2: List[String]) extends {
  val aList = l1
  val anotherList = l2
} with Foo

这将在调用断言之前启动列表,因此:

new Bar(List("a","b"),List("c","d")) // built successfully
new Bar(List("a","d","e")) // throws exception

当然 – 它并不完全是你所要求的(在构造之后总是被称为“钩子”),因为任何扩展类都必须知道哪些成员必须“早”被覆盖,但据我所知,这是你最接近的得到.

(编辑:李大同)

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

    推荐文章
      热点阅读