Using scala constructor to set variable defined in trait

[亡魂溺海] 提交于 2019-12-02 17:52:27

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!