Scala covariance error in Scala

I tried to compile the following code snippet:

class A[-T]
class B[-T] extends A[A[T]]

I get the following error:

error: contravariant type T occurs in covariant position in type [-T]A[A[T]]{def <init>(): B[T]} of class B

Why is this a mistake?

+4
source share
2 answers

This is a mistake because it A[A[T]]is covariant in type T.

Definition of covariant type from Wikipedia :

In the type system of a programming language, input rules or type of constructor:

  • covariant, if it preserves type ordering (≤), which orders types from more specific to more general;
  • contravariant if he changes this ordering;

Consider the following:

class Fruit
class Banana extends Fruit

and

Banana <: Fruit
A[Banana] :> A[Fruit] // Because A is contravariant in type T
A[A[Banana]] <: A[A[Fruit]] // Again because A is contravariant in type T

, A[A[T]] , .

:

scala> type AA[+T] = A[A[T]]
defined type alias AA

scala> type AAA[-T] = A[A[A[T]]]
defined type alias AAA

:

scala> type AA[-T] = A[A[T]]
<console>:15: error: contravariant type T occurs in covariant position in type [-T]A[A[T]] of type AA
       type AA[-T] = A[A[T]]
            ^

scala> type AAA[+T] = A[A[A[T]]]
<console>:15: error: covariant type T occurs in contravariant position in type [+T]A[A[A[T]]] of type AAA
       type AAA[+T] = A[A[A[T]]]
            ^

, , class B, A[A[T]] T .

, , , :

class B[-T] extends A[A[T]]

:

B[Fruit] <: B[Banana] <: A[A[Banana]] 

val fruits: B[Fruit] = new B[Fruit]
val bananas1: B[Banana] = fruits
val bananas2: A[A[Banana]] = bananas1      

bananas2 A[A[Banana]], A[A[Fruit]], , A[A[Banana]] <: A[A[Fruit]].

+4

<init> A ( B), .

, B[-T] extends A[A[T]] .

:

class A[-T]
class B[-T] extends A[A[T]]

class Animal
class Cat extends Animal

A <: B, , A B.

A B T Cat <: Animal,

A[Animal] <: A[Cat]
B[Animal] <: B[Cat]

A[Animal] <: A[Cat], ( - A):

A[A[Cat]] <: A[A[Animal]]

, B:

B[Cat] = A[A[Cat]]
B[Animal] = A[A[Animal]]

, B[Animal] <: B[Cat], , :

B[Animal] <: B[Cat] => A[A[Animal]] <: A[A[Cat]]

, A[A[Cat]] <: A[A[Animal]]. .

+2

Source: https://habr.com/ru/post/1660095/


All Articles