Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a Trait extending Abstract Class with non-empty constructor compiles?

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...

like image 916
NightWolf Avatar asked Sep 29 '22 18:09

NightWolf


1 Answers

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
like image 67
Arie Xiao Avatar answered Oct 29 '22 04:10

Arie Xiao