Traits cannot have constructor arguments. So how is it possible to write a trait which extends and abstract class which has a non-empty constructor?
abstract class HasConsArgs(val i: Int)
trait Test extends HasConsArgs
Which compiles. But when trying to use;
new Test {}
You get a error not enough arguments for constructor HasConsArgs: ...
... Why is this the case, is it possible to have an implementer of a trait call this constructor somehow?
class Impl(i: Int) extends Test //doesnt work
Fails with error: not enough arguments for constructor HasConsArgs: (i: Int)HasConsArgs.
which means that I probably need to have Impl
extend the HasConsArgs
abstract class...
In your case, you cannot create an anonymous class using Test
, because you cannot specify the super constructor arguments, as you've seen.
If a trait extends a class, all the classes that mixin the trait has to be either a subclass of that class or a descendant class of that class.
class A
class B extends A
class C
trait D extends A
class E extends D
class F extends A with D
class G extends B with D
class H extends C with D // fails
In order to mixin Test
trait, you can write
class Impl(i: Int) extends HasConstArgs(i) with Test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With