I found an interesting condition with traits:
scala> trait Thing[A]
defined trait Thing
scala> val myThing: Thing[Int] = new Thing[Int]
error: trait Thing is abstract; cannot be instantiated
scala> val myThing: Thing[Int] = new Thing[Int] { }
myThing: Thing[Int] = $anon$1@135f160e
Why does having the code block allow me to create an instance of the Thing trait?
It's a feature of the language called an anonymous class. When you write new Thing[Int] { }, the compiler creates a new class with the name $anon$1 (or something similar) that extends Thing[Int], and then creates a new instance of $anon$1.
You cannot instantiate the trait directly. When adding the {}, you're creating an anonymous class which can be instantiated.
Similar question posted elsewhere:
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