Given the below example, how can I make the code compile without resorting to casting in myMethod?
object Test {
sealed trait MyTrait
case class A(v: Int) extends MyTrait
case class B(v: Int) extends MyTrait
def myMethod[T <: MyTrait](in0: T): T = {
in0 match {
case in: A => in.copy(v = 1)
case in: B => in.copy(v = 2)
}
}
}
Thanks.
You can try to:
identityinvalueFor instance you could implement it like this
It will make mismatching types error go away. Instead you will get warning that
which in turn could be suppressed with
@nowarn.However, to be honest in such cases when I know that I know better than the compiler - because code is trivial and obvious at a glance, and I also cover it with tests -
.asInstanceOfis not that bad. Sometimes you cannot avoid it so it's good to create some small, well tested utility which will help to deal with all cases where compiler was not so smart.