Scala trait 可以有 vars,而不仅仅是 vals 吗? [英] Can Scala traits have vars, not just vals?

查看:37
本文介绍了Scala trait 可以有 vars,而不仅仅是 vals 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Scala 特征,但尚未对其进行编程,因此这是一个假设性问题.

I'm looking at Scala traits, but have yet to program in it, making this a hypothetical question.

到目前为止,我看到的所有示例都有具体或抽象的字段,它们仅在声明中使用 val 而不是 var.使用 var 声明的字段可以在 Scala trait 中使用吗?

All of the examples that I've seen so far have concrete or abstract fields that only use val in their declaration instead of var. Can fields declared with var be used in Scala traits?

TIA,马修

推荐答案

如果你尝试你会看到它有效:

If you try it you'll see it works:

scala> trait TestTrait {
     | var x = 1
     | }
defined trait TestTrait

scala> val t = new TestTrait { }
t: TestTrait = $anon$1@4c32060c

scala> t.x = 2
t.x: Int = 2

scala> t.x
res0: Int = 2

如果您了解 varval 在 Scala 中是如何编译的,这是有道理的.val 是具有自动生成的 getter 方法的私有字段,而 var 的唯一区别是它也有一个 setter.

If you read into how var and val are compiled in Scala this makes sense. A val is a private field with an auto-generated getter method, and the only difference for a var is that is has a setter as well.

这篇关于Scala trait 可以有 vars,而不仅仅是 vals 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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