开发者

What does "trait A <: B" mean?

In Scala, what does

trait A <: B

mean? Is it just the same as

trait A extends B

?

Edited to add: I'm familiar with the syntax for type parameters, and what <: means in that context. However, in the above example it would seem to me that A开发者_C百科 is the name of the trait being declared, not a type parameter.


NOTE As of Scala 2.12.5 using <: for extends is deprecated

scala -deprecation -e 'trait B; trait A <: B'
/var/folders/0w/kb0d3rqn4zb9fcc91pxhgn8w0000gn/T/scalacmd2374381600671257557.scala:1: warning: Using `<:` for `extends` is deprecated
trait B; trait A <: B
                 ^
one warning found

Seems to compile to the same thing.

 ~/code/scratch: scala -Xprint:typer -e 'trait B; trait A <: B'
          // snip
          abstract trait B extends scala.AnyRef;
          abstract trait A extends java.lang.Object with this.B

 ~/code/scratch: scala -Xprint:typer -e 'trait B; trait A extends B'
          // snip
          abstract trait B extends scala.AnyRef;
          abstract trait A extends java.lang.Object with this.B    

The spec doesn't explain this in "5.3.3 Traits". But the Syntax Summary does mention this.

TraitDef ::= id [TypeParamClause] TraitTemplateOpt 
TraitTemplateOpt ::= Extends TraitTemplate | [[Extends] TemplateBody]
Extends ::= ‘extends’ | ‘<:’

UPDATE It was introduced in r14632. With the compiler option -Xexperimental it marks the trait as abstract, for use with a proposed language feature Virtual Traits. Without -Xexperimental, it is a synonym for 'extends' that is allowed only for traits.


The <: syntax is reserved for future use in virtual classes (which are not implemented yet).


Looking at the Scala Language Specification, it seems to mean the same thing. The description for trait only mentions the trait A extends B syntax. But the Scala syntax summary uses extends and <: interchangeably for trait definitions:

TraitTemplateOpt ::= Extends TraitTemplate | [[Extends] TemplateBody]
Extends ::= ‘extends’ | ‘<:’ 


Yes, well, almost, see this article for a little more information. From the language spec, we see the following definition:

We define two relations between types.

Type equivalence T ≡ U T and U are interchangeable in all contexts.

Conformance T <: U Type T conforms to type U .

Edit: Looking into the language spec it appears that <: and extends are the same, in particular it is defined as:

ClassTemplateOpt ::= Extends ClassTemplate | [[Extends] TemplateBody]
TraitTemplateOpt ::= Extends TraitTemplate | [[Extends] TemplateBody]
Extends ::= ‘extends’ | ‘<:’


Please note that as of Scala 2.12.5:

Using <: for extends is deprecated

$ scala -deprecation -e 'trait B; trait A <: B'
/var/folders/0w/kb0d3rqn4zb9fcc91pxhgn8w0000gn/T/scalacmd4147407032094171597.scala:1: warning: Using `<:` for `extends` is deprecated
trait B; trait A <: B
                 ^
one warning found
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜