Display a list of existential types

I have a list of object-typed objects that I want to display. Something like that:

sealed abstract class IntBox(val v: Int)
case object IB1 extends IntBox(1)
case object IB2 extends IntBox(2)

case class Adder[A  <: IntBox](ib: A, v: Int) {
  def add(i: A) = v + i.v
}

val adders: List[Adder[_ <: IntBox]] = List(Adder(IB1, 0), Adder(IB2, 0))

adders.map(adder => adder.add(adder.ib))

However, I get an error, for example

found: adder.ib.type
required: _$1

I feel like it's like mapsomehow merging different IntBoxinto one unreachable anonymous type ...

Can I get what I want without casting (i.e. adder.asInstanceOf[Adder[adder.ib.type]]...?

+1
source share
1 answer

The type is not available, you can get it by matching type templates:

adders.map{ case a: Adder[t] => a.add(a.ib) }

Here, an existential type parameter is bound to a variable type t, and the compiler can correctly infer additional properties tthat it cannot do for the entire list.

. 8.3.1 .


trait class,

sealed abstract class IntBox(val v: Int)
case object IB1 extends IntBox(1)
case object IB2 extends IntBox(2)

case class Adder[A  <: IntBox](ib: A, v: Int) {
  def add(i: A) = v + i.v
}

val adders: List[Adder[_ <: IntBox]] = List(Adder(IB1, 0), Adder(IB2, 0))

adders.map{ case a: Adder[t] => a.add(a.ib) }
+2

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


All Articles