Jaxidoxium
Jaxidoxium

Reputation: 33

Case class .copy with upperbound value

I'm having problems using the .copy method of a case class which has an upper bound value. The example is something like this:

sealed abstract class SomeOtherClass[A <: SomethingElse]{...}

final case class SomeClass[LI <: SomeOtherClass[_]](
    value1: String,
    value2: LI)

And in another part of my code I have:

val instance: SomeClass(_) = service.getInstance()
...
instance.copy(value1 = "Something new")

But when I try to rung my code I get an error saying something along the lines:

type mismatch;
[error]  found   : List[_$2]
[error]  required: List[LI]

The question is, is there a way to use the .copy method for something like this? Or what would be the recommended way to do so?

Upvotes: 1

Views: 81

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

Try bounding the existential type like so

val instance: SomeClass[_ <: SomeOtherClass[_]] = service.getInstance()

corresponding to LI <: SomeOtherClass[_]. For example,

trait Animal
case class Cat() extends Animal
case class Dog() extends Animal

sealed abstract class House[A <: Animal](a: A)
case class DogHouse(dog: Dog) extends House(dog)
case class CatHouse(cat: Cat) extends House(cat)

final case class SomeClass[LI <: House[_]](value1: String, value2: LI)

val instance: SomeClass[_ <: House[_]] = SomeClass("Floppy", DogHouse(Dog()))
instance.copy(value1 = "Something new") // res0: SomeClass[_$2] = SomeClass(Something new,DogHouse(Dog()))

Upvotes: 3

Related Questions