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.
Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.
Traits are reusable components that can be used to extend the behavior of classes. They are similar to interfaces and contain both abstract and concrete methods and properties.
The sealed is a Scala keyword used to control the places where given trait or class can be extended.
Syntax: class Class_Name extends Trait_Name1 with Trait_Name2 with Trait_Name3{ // Code.. } An abstract class can also inherit traits by using extends keyword. In Scala, one trait can inherit another trait by using a extends keyword.
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
A
takes a constructor argument, so you are required to pass it, e.g.
new A("someName") with E
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