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?
Barmust define the abstractvar fooinFoo(would be the same for aval). This can be done in the constructor(of course, it could be done in the body of
Bartoo). By default, constructor parameters will be turned to privatevalif need be, that is if they are used outside the initiailization code, in methods. But you can force the behavior by marking themvalorvar, and possibly control the visibility as inHere you need a public
varto implementFoo.