Scala:用于早期定义/早期初始化器/预初始化字段的示例 [英] Scala: Example use for early definition / early initializer / pre-initialized fields

查看:26
本文介绍了Scala:用于早期定义/早期初始化器/预初始化字段的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 允许您像这样进行早期定义:

Scala allows you to make early definitions like so:

trait A {
  val v: Int
}

class B extends { val v = 4 } with A

此功能的使用示例是什么?

What is an example use of this feature?

推荐答案

每当该值用于特征初始化时.所以对于这个特性的例子:

Whenever the value is used for the trait initialization. So for eaxmple for this trait:

trait UsefulTrait {
  val parameter : Int
  private val myHelperObject = new MyExpensiveClass(parameter)
}

该参数用于替代构造函数参数.但是参数应该是一个抽象的方法,因为它给实现者留下了更多的自由空间.

The parameter is used to substitute for a constructor parameter. However the parameter should be rather made an abstract method, because it leaves more free space to the implementer.

这篇关于Scala:用于早期定义/早期初始化器/预初始化字段的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆