余杰水
余杰水

Reputation: 1384

what is the difference extends type and type

define Hello and World trait

trait Hello

trait World

this no problem

trait Right extends Hello with World

but this have a compile error

type HelloWorld = Hello with World

trait Error extends HelloWorld
//Error:(9, 22) class type required but A$A65.this.Hello with A$A65.this.World found

Upvotes: 1

Views: 77

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170733

You can only have a class or a trait after extends, and Hello with World is neither (it is a compound type). extends Hello with World should be understood as "extends Hello with World", not as "extends Hello with World".

Upvotes: 3

Seth Tisue
Seth Tisue

Reputation: 30453

By SLS 5.3, trait Hello is short for trait Hello extends AnyRef ("The extends clause [...] can be omitted, in which case extends scala.AnyRef is assumed").

And according to SLS 5.1, "It is possible to write a list of parents that starts with a trait reference [...] In that case the list of parents is implicitly extended to include the supertype of mt1 as first parent type."

Therefore trait Right extends Hello with World is actually short for trait Right extends AnyRef with Hello with World.

As for why using a type alias messes things up, if you look at the syntax definitions, the syntax isn't extends <type>, it's literally extends <sc> with <mt1> with <mt2> .... The syntax for compound types is defined separately, in SLS 3.2.7. It looks like the same syntax, but it's not really the same.

Upvotes: 2

Related Questions