Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you instantiate a trait in scala?

Tags:

scala

Why can't I instantiate a trait? The compiler complains that the trait is abstract, but I don't have any abstract method or field in the trait.

scala> trait A
scala> new A
<console>:9: error: trait A is abstract; cannot be instantiated
              new A
              ^
like image 282
Daniel Wu Avatar asked Dec 19 '22 14:12

Daniel Wu


1 Answers

It fails because traits are always abstract by definition, like Java interfaces.

When you write new A {} it means "create an anonymous class extending A and create an instance of it". This anonymous class is, of course, not abstract, so this works.

like image 178
Alexey Romanov Avatar answered Jan 10 '23 11:01

Alexey Romanov