Reputation: 369
I know a trait can extend a class which has an empty parameter constructor:
class Foo
trait Bar extends Foo
but is it possible to extend a class which constructor has some parameters?
class Foo(b: Boolean)
trait Bar extends Foo(true)
Is it possible to achieve this? It seems it's not possible. but why?
Thanks
Upvotes: 11
Views: 424
Reputation: 170745
Yes, it's possible, you just can't give constructor arguments:
trait Bar extends Foo { ... }
But to instantiate it you need to call the constructor as well:
new Foo(false) with Bar
Upvotes: 4
Reputation: 51271
Making the arg a val
seems to work.
scala> class Foo(val b: Boolean)
defined class Foo
scala> trait Bar extends Foo {override val b = true}
defined trait Bar
This also works if you make the class a case class
which automatically turns the args in to vals.
EDIT
As @Aleksey has pointed out, this compiles but it's a trait that can't be instantiated so, no, it still doesn't seem possible. You'll have to make Bar a class.
scala> class Bar extends Foo(false) {println(b)}
defined class Bar
scala> new Bar
false
Upvotes: 2