Why is it possible to create several traits in Scala, but not one?

Let's say we have two features:

trait Trait1 trait Trait2 

If I try something like val single = new Trait1 , I get the error message error: trait Trait1 is abstract; cannot be instantiated error: trait Trait1 is abstract; cannot be instantiated . However, val twoTraits = new Trait1 with Trait2 compiles. Why is this so?

PS I also noticed that val single = new Trait1 {} compiles just fine. Could you give a correct explanation?

+5
source share
1 answer

Technically, you cannot instantiate a single trait or multiple mixed traits directly, but the compiler uses some syntactic sugar, which allows you to create anonymous classes that extend them. Say we have:

 trait A trait B 

When you call new A with B , what really happens, the compiler creates an anonymous class that mixes in both A and B You are getting:

 final class $anon extends A with B new $anon() 

When you call new A {} , the same thing happens. You get an anonymous class that extends A :

 final class $anon extends A new $anon() 

The only difference is syntactic. When creating an anonymous class from one attribute, you must at least use curly braces {} to distinguish it from the class. That is, it is easier to determine if a template can be constructed, or must be completed in an anonymous class to be created. With several attributes (or even a class with mixed attributes), the compiler realizes that he always needs to create an anonymous class first.

Summarizing:

 class C new A {} // Anonymous class that extends A, then constructed new A with B // Anonymous class that extends A with B, then constructed new C // Constructed instance of class C new C with A // Anonymous class that extends C with A, then constructed 
+8
source

Source: https://habr.com/ru/post/1264636/


All Articles