Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not instantiate trait with no methods without empty code block

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?

like image 332
Rob Avatar asked May 10 '26 07:05

Rob


2 Answers

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.

like image 169
Michael Zajac Avatar answered May 13 '26 09:05

Michael Zajac


You cannot instantiate the trait directly. When adding the {}, you're creating an anonymous class which can be instantiated.

Similar question posted elsewhere:

  • https://www.scala-lang.org/old/node/9297
  • https://www.reddit.com/r/scala/comments/9t1b9u/instantiation_of_traits/
like image 31
Dan W Avatar answered May 13 '26 11:05

Dan W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!