Reputation: 5424
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
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
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
Reputation: 10764
A
takes a constructor argument, so you are required to pass it, e.g.
new A("someName") with E
Upvotes: 2