In scala, is it possible for a trait to extend a class that needs parameters?

I know that a slash can extend a class that has an empty parameter constructor:

class Foo trait Bar extends Foo 

but is it possible to extend a class for which the constructor has some parameters?

 class Foo(b: Boolean) trait Bar extends Foo(true) 

Can this be achieved? It seems to be impossible. but why?

thanks

+8
inheritance scala extends traits
source share
2 answers

Yes, maybe you just can't give constructor arguments:

 trait Bar extends Foo { ... } 

But to create it, you also need to call the constructor:

 new Foo(false) with Bar 
+3
source share

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 create a case class that automatically turns args into vals.

EDIT

As @Aleksey noted, this compiles, but it is a trait that cannot be created in this way, no, it still is not possible. You have to make Bar a class.

 scala> class Bar extends Foo(false) {println(b)} defined class Bar scala> new Bar false 
+2
source share

All Articles