Daniel Wu
Daniel Wu

Reputation: 6003

Why can't you instantiate a trait in 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
              ^

Upvotes: 4

Views: 3533

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170909

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.

Upvotes: 11

Related Questions