Using scala constructor to set variable defined in trait

后端 未结 2 2046
花落未央
花落未央 2021-02-01 01:14

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 02:17

    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.

提交回复
热议问题