使用scala构造函数设置trait中定义的变量

发布于 2024-12-16 13:25:45 字数 322 浏览 2 评论 0原文

如果我理解正确的话,traits 是最接近 Java 接口的东西,类构造函数会自动设置变量。

但是,如果我有一个扩展特征的类,并且有一个从特征设置变量的构造函数,例如:

trait Foo {
    var foo: String
}

class Bar (foo: String) extends Foo { /* ... */ }

当我创建 < 时,我希望设置特征的 foo 字符串,该 怎么办? code>Bar 对象。

编译器似乎给了我关于此的错误。实现这一目标的正确方法是什么?

If I understand correctly, traits are the closest thing to Java interfaces and class constructors automatically set the variables.

But what if I have a class that extends a trait and has a constructor which sets a variable from the trait, so something like:

trait Foo {
    var foo: String
}

class Bar (foo: String) extends Foo { /* ... */ }

Where I want the foo string of the trait been set when I make a Bar object.

The compiler seems to give me errors about this. What is the correct way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江城子 2024-12-23 13:25:45
trait Foo { var foo: String = _ }
class Bar(foo0: String) extends Foo { foo = foo0 }

该特征声明了一个未初始化的变量;然后该类将其设置为等于输入参数。

或者,

trait Foo {
  def foo: String
  def foo_=(s: String): Unit
}
class Bar(var foo: String) extends Foo {}

声明与 foo 相对应的 getter/setter 对,它们由类设置。

trait Foo { var foo: String = _ }
class Bar(foo0: String) extends Foo { foo = foo0 }

The trait declares an uninitialized var; the class then sets it equal to the input parameter.

Alternatively,

trait Foo {
  def foo: String
  def foo_=(s: String): Unit
}
class Bar(var foo: String) extends Foo {}

declares the getter/setter pair corresponding to a foo, which are set by the class.

爱要勇敢去追 2024-12-23 13:25:45

Bar 必须在 Foo 中定义抽象 var foo(与 val 相同)。这可以在构造函数中完成

class Bar(var foo: String) extends Foo{...}

(当然,也可以在 Bar 主体中完成)。默认情况下,如果需要的话,构造函数参数将被转换为私有val,即如果它们在初始化代码之外的方法中使用。但是您可以通过标记它们 valvar 来强制执行该行为,并可能控制可见性,如

class X(protected val s: String, private var i: Int)

这里您需要一个公共 var 来实现 <代码>Foo。

Bar must define the abstract var foo in Foo (would be the same for a val). This can be done in the constructor

class Bar(var foo: String) extends Foo{...}

(of course, it could be done in the body of Bar too). By default, constructor parameters will be turned to private val if need be, that is if they are used outside the initiailization code, in methods. But you can force the behavior by marking them val or var, and possibly control the visibility as in

class X(protected val s: String, private var i: Int)

Here you need a public var to implement Foo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文