epr*_*rst 6 types scala structural-typing compound-type
为什么不允许出现以下情况?(2.12):
type Foo <: {def foo(): Unit}
type Bar <: {def bar(): Unit} with Foo
Run Code Online (Sandbox Code Playgroud)
对我来说看起来很自然,Bar应该同时具有foo()和bar()。
似乎与括号一起工作
scala> type Foo <: {def foo(): Unit}
| type Bar <: ({def bar(): Unit}) with Foo
type Foo
type Bar
Run Code Online (Sandbox Code Playgroud)
type Foo <: {def foo(): Unit}是type Foo <: AnyRef{def foo(): Unit}。
所以虽然type Bar <: {def bar(): Unit} with Foo不可解析,AnyRef但它的工作顺序不同
type Foo <: {def foo(): Unit}
type Bar <: Foo with AnyRef{def bar(): Unit}
val b: Bar = ???
b.foo()
b.bar()
Run Code Online (Sandbox Code Playgroud)
也有括号(和直接订单)它的工作原理
type Foo <: {def foo(): Unit}
type Bar <: ({def bar(): Unit}) with Foo
val b: Bar = ???
b.foo()
b.bar()
Run Code Online (Sandbox Code Playgroud)
实际上type Bar <: {def bar(): Unit} with Foo是违反规范而type Bar <: ({def bar(): Unit}) with Foo满足规范的,因为{def bar(): Unit}它不是 aSimpleType而是({def bar(): Unit})a SimpleType。
CompoundType ::= AnnotType {‘with’ AnnotType} [Refinement]
| Refinement
AnnotType ::= SimpleType {Annotation}
SimpleType ::= ............
| ‘(’ Types ‘)’
Types ::= Type {‘,’ Type}
Type ::= ...........
| CompoundType
| ...........
Run Code Online (Sandbox Code Playgroud)
https://scala-lang.org/files/archive/spec/2.13/03-types.html#compound-types