Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate trait which extends class with constructor

Tags:

scala

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.

like image 415
ka4eli Avatar asked Apr 19 '14 09:04

ka4eli


People also ask

Can I use constructor in trait?

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.

Can traits extend 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.

Which keyword is used to control the places where given trait or class can be extended in Scala?

The sealed is a Scala keyword used to control the places where given trait or class can be extended.

How do you extend a trait and a class in Scala?

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.


2 Answers

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
like image 198
Yuriy Avatar answered Oct 05 '22 18:10

Yuriy


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

new A("someName") with E
like image 20
ghik Avatar answered Oct 05 '22 17:10

ghik