V
V
Vi Vola2020-10-18 13:19:50
Scala
Vi Vola, 2020-10-18 13:19:50

How to concatenate sequences in a parameterized class?

I'm learning about polymorphism in Scala and can't figure out the following question.
For example, there is some class hierarchy:

class A
class B extends A
class C extends B

And there is some class whose constructor takes a sequence of elements and a push method that takes a new sequence of elements, concatenates it with an existing sequence, and returns a new Foo .

class Foo[T](a: Seq[T]) {
  def push[T](b: Seq[T]): Foo[T] = {
    new Foo(a ++ b)           // тут получаю ошибку - type mismatch; found : Seq[Any]; required: Seq[T]
  }
}

But in my case it does not work and I do not quite understand why it is cast in .Seq[T]Seq[Any]

val foo = new Foo(Seq(new C, new C))
val bar = foo.push(Seq(new B, new B))
println(bar) // должен содержать [C, C, B, B]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vi Vola, 2020-10-19
@hakain

class Foo[T](a: Seq[T]) {
  def push[U >: T](b: Seq[U]): Foo[U] = {
    new Foo(a ++ b)
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question