Using scala constructor to set variable defined in trait

后端 未结 2 2049
广开言路
广开言路 2021-02-01 01:32

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 extend

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 01:59

    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.

提交回复
热议问题