https://kotlinlang.org logo
Title
a

awzurn

02/27/2019, 12:18 AM
Has anyone else run into a use-case of wanting to be able to copy a data class with a generic field, where the new value being provided (for the generic field) is a different type? I recently ran into when I was using a data class as a message wrapper for a parsed message (which included both the parsed typed entity and the payload it was parsed from). Scala support something like this with their `case class`:
scala> case class Something[T](something: T)
defined class Something

scala> Something(1)
res0: Something[Int] = Something(1)

scala> res0.copy(something = "something")
res1: Something[String] = Something(something)
Kotlin, on the other hand, won’t compile something like this:
data class Something<T>(val value: T)
Something(1).copy("something")
I’m wondering if it was an explicit design decisions, or maybe something that just hasn’t been implemented yet?
s

Sander Ploegsma

02/27/2019, 7:43 AM
You could easily do it yourself though, right?
data class Something<T>(val value: T) {
  fun <U> myCopy(newValue: U) = Something(newValue)
}
Although I'm guessing that this doesn't scale well for large data classes, so I get your question.
a

awzurn

02/27/2019, 4:05 PM
Right. Not a huge deal by any means, just found it curious (I recently moved from using Scala to Kotlin as a primary). But yes, not necessarily scalable either for large classes nor having multiple classes.
s

Sander Ploegsma

02/28/2019, 7:34 AM
I must say that I personally never felt the need for it anyway, I'm wondering if there is another way to approach your specific problem