Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Members and Covariance

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 ?

like image 407
Michael Avatar asked Mar 18 '11 11:03

Michael


People also ask

What is the difference between covariance and contravariance in delegates?

Covariance permits a method to have return type that is more derived than that defined in the delegate. Contravariance permits a method that has parameter types that are less derived than those in the delegate type.

What is covariance and contravariance in generics?

Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.

Why is covariance and contravariance important?

In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.


1 Answers

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.

like image 143
psp Avatar answered Oct 13 '22 08:10

psp