Scala covariant type error

I tried to define a class

abstract class Sequence[+A] {
    def append (x: Sequence[A]): Sequence[A]
}

and got into the terminal

<console>:8: error: covariant type A occurs in contravariant position in type Sequence[A] of value x
           def append (x: Sequence[A]): Sequence[A]

Why is this definition not OK and what would be the best way to fix this? I checked this covariant type T occurs in a contravariant position , but nothing helps me.

+4
source share
2 answers

It works:

abstract class Sequence[+A]{
  def append[B >: A](x: Sequence[B]): Sequence[B]
}

When you define a covariant type, you cannot use it as an input parameter (you will have the same problem with the contravariant type that is used for the return type). A workaround is to define a new type (here B), which is super-type A.

+5
source

, Scala, @vptheron . "" , Scala .

Sequence[+A], , B A, Sequence[B] Sequence[A].

, , ( ) .

:

class IntSequence extends Sequence[Int] {
  override def append(x: Sequence[Int]) = {
    println(math.sqrt(x.head))
    //makes no sense but humor me
  }
}

A , Int Any, Sequence[Int] Sequence[Any]. .

StringSequence, IntSequence.

:

val x:Sequence[Any] = new IntSequence
val ss:Sequence[Any] = new StringSequence
//Let ss be populated somehow
x.append(ss)

, . IntSequence Sequence[Int], Sequence[Int] Sequence[Any] .

, . .

( ) , . Sequence[String] Sequence[Any], Sequence[String] Sequence[Any].

, , Sequence[String], x IntSequence.

" 13", ", ".

. , , , , , ​​.

, . , .

, , , @vptheron.

, .

+6

All Articles