How do I return a copy of a generic case class using the case class .copy
method?
I’m trying to achieve the following:
def modifyNumber[T <: { def number: Int }](objectWithNumber: T, numberToReplace: Int): T = {
objectWithNumber.copy(number = numberToReplace)
}
but I get the error:
value copy is not a member of type parameter T
objectWithNumber.copy(number = numberToReplace)
These case classes from from an automated ORM process so I can’t directly extend them. Is there a way around that?
Here’s an example of a few case classes:
case class One(someText: String, number: Int)
case class Two(otherStuff: List[Long], number: Int)
I’m able to create generic functions which I can pass either of these two case classes like so:
def addNumber[T <: { def number: Int }](objectWithNumber: T, numberToAdd: Int): Int = {
objectWithNumber.number + numberToAdd
}
I also tried:
def modifyNumber[T <: Product with Serializable { def number: Int }](objectWithNumber: T, numberToReplace: Int): T = {
objectWithNumber.copy(number = numberToReplace)
}
but with this I get the same error.
How can I implement modifyNumber
such that it can return a copy of the generic? Is this possible on Scala 2.13.10 (the version I’m on).