ka4eli
ka4eli

Reputation: 5424

How to instantiate trait which extends class with constructor

Have a code:

class A(name:String)
trait E extends A

new E{}  //compile error

Is such inheritance possible? Tried to create val or def in the body of anonymous class, doesn't help.

Upvotes: 16

Views: 3916

Answers (3)

Eugene Zhulenev
Eugene Zhulenev

Reputation: 9734

If you want to restrict trait E to be mixed with class A only you can use self type. However this is no way to define variable as new E with A(...)

class A(val name: String)

trait E { self: A =>
  def printName() = println(self.name)
}

val e = new A("This is A") with E
e.printName()

Upvotes: 1

Yuriy
Yuriy

Reputation: 2769

Few possible solutions:

1) set default value for name in class A constructor:

class A(name : String = "name")
trait E extends A
new E {} // {} is obligatory. trait E is abstract and cannot be instantiated`

2) mix trait E to instance of A:

object inst extends A("name") with E
// or:
new A("name") with E

Upvotes: 14

ghik
ghik

Reputation: 10764

A takes a constructor argument, so you are required to pass it, e.g.

new A("someName") with E

Upvotes: 2

Related Questions