Why is overriding an already implemented abstract type not possible?
Asked Answered
A

1

8

Given the following code:

class A {

  class B

  type C <: B

  trait D

}

class E extends A {

  type C = B

}

class F extends E {

  override type C = B with D

}

Why does the Scala IDE's presentation compiler within the Eclipse Indigo IDE complain with the error message overriding type C in class E, which equals F.this.B; type C has incompatible type?

After all class "B" is only "amended" with trait "D" and thus the two type definitions are of the same base type, which is "B". Hence compatible type definitions.

The code below works. I consider the rules for type assignment similiar to variable assignment, such as:

class Foo

trait Bar

val a: Foo =  new Foo

val fooWithBar: Foo = new Foo with Bar

Is my understanding wrong?

Audiophile answered 7/1, 2012 at 16:38 Comment(1)
Foo with Bar is a subtype of Foo. This is not what the problem is. You are not allowed to redefine a type member while it is fixed, even to a subtype. If you had class Bar extends Foo, you could not redefine a type member from Foo to Bar either.Chambermaid
C
14

They are not compatible, type C might be used in a contravariant position

class E extends A {
  type C = B
  def f(c: C)
}


class F extends E {
  override type C = B with D 
  def f(c: ???)
}

Complement given e: E, you are allowed to call e.f(new B). What if e was val e = new F ?

Chambermaid answered 7/1, 2012 at 17:26 Comment(3)
Why should this constellation be unsound as long as the overridden type "C" is further restricted and keeps its base type "B". If method "f" accepts "B"s why shouldn't it accept subclasses hereof, as per redefinition "B with D"s?Audiophile
If the method accepts B, certainly it must accepts subtypes. The problem is that instances of F will require B with D, and so not longer accept simple B. A subtype of E must accepts B in f. It will of course accepts subtypes. It cannot require the argument to be a subtype.Chambermaid
I'm not sure this is the correct counter example. Here's why: ( sorry, disregard, I was trying to hit cancel on my phone, but it got posted instead..)Manifestation

© 2022 - 2024 — McMap. All rights reserved.