structural type extending another structural type

211 Views Asked by At

Why the following is not allowed? (2.12):

type Foo <: {def foo(): Unit}
type Bar <: {def bar(): Unit} with Foo

Looks natural to me, Bar should have both foo() and bar().

3

There are 3 best solutions below

0
Dmytro Mitin On BEST ANSWER

type Foo <: {def foo(): Unit} is type Foo <: AnyRef{def foo(): Unit}.

So while type Bar <: {def bar(): Unit} with Foo is not parsable, with AnyRef and different order it works

type Foo <: {def foo(): Unit}
type Bar <: Foo with AnyRef{def bar(): Unit}

val b: Bar = ???
b.foo()
b.bar()

Also with brackets (and direct order) it works

type Foo <: {def foo(): Unit}
type Bar <: ({def bar(): Unit}) with Foo 

val b: Bar = ???
b.foo()
b.bar()

Actually type Bar <: {def bar(): Unit} with Foo is against the spec while type Bar <: ({def bar(): Unit}) with Foo satisfies the spec because {def bar(): Unit} is not a SimpleType but ({def bar(): Unit}) is a SimpleType.

CompoundType    ::=  AnnotType {‘with’ AnnotType} [Refinement]
                  |  Refinement

AnnotType       ::=  SimpleType {Annotation}

SimpleType      ::= ............
                  |  ‘(’ Types ‘)’

Types           ::=  Type {‘,’ Type}

Type            ::=  ...........
                  |  CompoundType
                  |  ...........

https://scala-lang.org/files/archive/spec/2.13/03-types.html#compound-types

0
Mario Galic On

Seems to work with parenthesis

scala> type Foo <: {def foo(): Unit}
     | type Bar <: ({def bar(): Unit}) with Foo
type Foo
type Bar
6
Martijn On

It's not allowed by the spec, which calls the { ...} part a refinement which may both have a with clause. The other way around it's fine though.

That's somewhat tautological of course as it doesn't say why it's not allowed by the spec. It appears there is no deep understanding here, just that that's not a way you're allowed to write a type. You should be able to express the same intent in another way.