copy method and subtype polymorphism in Scala

277 views Asked by At

I am trying to solve the following Scala compiler error below.

case class CC[E](l:List[E])

trait D[E,L<:CC[E]]{
  def f(l:L):L = l.copy(l=List()) // does not compile: "found CC[E], required: L"
}

In (pseudo)-Haskell (without sub-typing) this would be something like :

 data CC = CC {l::[e]}
 'makeLens CC
 f l = l .~ _e []

Currently I am looking into ScalaZ, Shapeless and Monocle.

On a first glance Monocle seems to be out of question (not sure though), please prove me wrong, if my intuition is wrong.

ScalaZ + Shapeless might probably work, I am unsure how (never used them).

1) What would be the easiest way to solve this in Scala ?

2) Would ScalaZ in itself be enough ? Or Shapeless in itself is enough ? Or is the combination of the two neccessary ? Or maybe some other way ?

1

There are 1 answers

2
Julien Truffaut On

You could do the following with Monocle:

import monocle.macros.Lenses

@Lenses
case class CC[E](l:List[E])

object D {
  def f[E](cc: CC[E]): CC[E] = CC.l.set(List())(cc)
}