Using scala constructor to set variable defined in trait

Seba Kerckhof picture Seba Kerckhof · Nov 18, 2011 · Viewed 34.7k times · Source

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

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

Answer

Rex Kerr picture Rex Kerr · Nov 18, 2011
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.