11

I guess, "type variance annotations" (+ and -) cannot be applied to "type members". In order to explain it to myself I considered the following example

abstract class Box {type T; val element: T}

Now if I want to create class StringBox I have to extend Box:

class StringBox extends Box { type T = String; override val element = ""}

So I can say that Box is naturally covariant in type T. In other words, the classes with type members are covariant in those types.

Does it make sense ?
How would you describe the relationship between type members and type variance ?

Michael
  • 10,185
  • 12
  • 59
  • 110

1 Answers1

16

Box is invariant in its type T, but that doesn't mean there's nothing to see.

abstract class Box {
  type T
  def get: T
}
type InvariantBox = Box { type T = AnyRef }
type SortofCovariantBox = Box { type T <: AnyRef }

What alters the variance situation is the degree to which the type is exposed and the manner it is done. Abstract types are more opaque. But you should play with these issues in the repl, it's quite interesting.

# get a nightly build, and you need -Ydependent-method-types
% scala29 -Ydependent-method-types

abstract class Box {
  type T
  def get: T
}
type InvariantBox = Box { type T = AnyRef }
type SortofCovariantBox = Box { type T <: AnyRef }

// what type is inferred for f? why?
def f(x1: SortofCovariantBox, x2: InvariantBox) = List(x1, x2)

// how about this?
def g[U](x1: Box { type T <: U}, x2: Box { type T >: U}) = List(x1.get, x2.get)

And etc.

Tvaroh
  • 6,645
  • 4
  • 51
  • 55
psp
  • 12,138
  • 1
  • 41
  • 51
  • Wow, your example blew my mind. It took me half an hour to figure out the correct types: The idea is that f can result in a List[AnyRef] at the top of the hierarchy, but it can actually result in a more specific type due to the nature of the polymorphic AnyRef, so f results in a List[SortofCovariantBox]. For g, x1 can result in a Box[U] at the top of the hierarchy, while x2 can result in a Box[U] where T = U at the bottom of the hierarchy, but T can be any supertype of U, so practically g results in a List[x2.T]. – Alin Gabriel Arhip Jun 15 '22 at 04:32