使用scala构造函数设置在trait中定义的变量 [英] Using scala constructor to set variable defined in trait

查看:778
本文介绍了使用scala构造函数设置在trait中定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对scala很新,如果我理解正确:traits是最接近的java接口&类构造函数自动设置变量。

I'm pretty new to scala and if I understand correctly: Traits are the closest thing to java interfaces & class constructors automatically set the variables.

但是如果我有一个类扩展trait并且有一个构造函数从trait设置一个变量, / p>

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{...}

我想要的trai的foo字符串设置当我做一个Bar对象。

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 would be the correct way to achieve this?

感谢

推荐答案

Bar 必须定义 Foo 中的抽象 var foo 对于 val 将是相同的)。这可以在构造函数中完成

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{...}

(当然,可以在 Bar 太)。默认情况下,如果需要,构造函数参数将转为private val ,即如果它们在初始化代码之外,在方法中使用。但是你可以通过标记它们来强制行为: val var

(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)

这里需要一个公共 var 来实现 Foo

Here you need a public var to implement Foo.

这篇关于使用scala构造函数设置在trait中定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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