Make42 Make42 - 1 month ago 9
Scala Question

Object with MyTrait {}

new MyTrait
leads to "trait MyTrait is abstract; cannot be instantiated" but
new MyTrait {}
actually leads to an instance of type
java.lang.Object with MyTrait
. I can understand what is happening (with
java.lang.Object
being sort of a default instance), but what is the role of the
{...}
here? Is this an anonymous implementation?

Answer

When you do {} you're basically saying "let's instance an object with the given trait, where the abstract part is implemented just once for this instance". So yeah, it's basically an anonymous class that has your trait and can implement all the abstract parts. In this case there are no abstract parts and so {} is enough.

Comments