如何初始化作为 val 的特征变量 [英] How to initialize a trait variable that is a val

查看:18
本文介绍了如何初始化作为 val 的特征变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 MyObject 和 MyTrait:

I have MyObject and MyTrait:

class MyObject(private val myname: String = "") extends MyTrait {

  _name = myname

  def foo(myname : String) {
   _name = myname
  }
}

trait MyTrait {

  protected var _name: String = _

  def name = _name

}

这很好用

val myObject = new MyObject("abc")
println(myObject.name)
myObject.foo("def")
println(myObject.name)

印刷品

abc
def

正如预期的那样.

现在的问题是我希望 MyTrait._name 是一个 val 而不是 var.但是我无法设法编译它.任何提示表示赞赏.

Problem now is that I want MyTrait._name to be a val instead of a var. But there is no way I can manage to get this to compile. Any hints appreciated.

问候,奥利弗

推荐答案

这是一个使用 Rex Kerr 和 Martin Odersky 最新前沿命名约定的答案!

Here is an answer that uses the very latest cutting-edge naming conventions from Rex Kerr and Martin Odersky!

scala-debate 列表上阅读.你认为他们坐在那里研究更高种类"并使用未装箱的整数进行计算.

Read it on the scala-debate list. And you thought they sit around working on "higher kinds" and computing with unboxed ints.

对于样式更改有一个PR,但是这个约定需要等待位.

There is a PR for the style changes, but this convention will have to wait a bit.

Doc Martin 说:这看起来很有希望.我必须尝试一下.

Doc Martin says: That does look promising. I have to experiment with it a little.

所以要小心这些东西;它是实验性的,可能在化学上不稳定.

So be careful with this stuff; it's experimental and probably chemically unstable.

class MyObject(override protected val initialName: String = "") extends MyTrait {

  private var myName: String = initialName

  def name_=(newName: String) {
    myName = newName
  }
  override def name = myName
}

trait MyTrait {
  protected val initialName: String = "default"
  def name = initialName
}
object Test extends App {
  val myObject = new MyObject("abc")
  println(myObject.name)
  myObject.name = "def"
  println(myObject.name)
}

风格指南 有一个关于简洁的部分,但它本身并不简短.我敢肯定,丹尼尔·索布拉尔 (Daniel Sobral) 有关于更喜欢 def 而不是 val in traits"的答案.当您遇到初始化顺序问题时,不要忘记查阅一问常见问题.

The style guide has a section on brevity but is itself not brief. I'm sure there are answers on SO about "prefer def over val in traits" by Daniel Sobral. And don't forget to consult the one-question FAQ when you encounter init-order problems.

这篇关于如何初始化作为 val 的特征变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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