natpryce
10/29/2025, 7:47 AMdata class Basket<Fruit>(fruit: Set<Fruit>)
And an instance of it:
val bananas : Basket<Banana>
The type checker does not allow:
val apples : Basket<Apple> = bananas.copy(fruit = listOf(apple1, apple2))
Instead, I have to call the constructor of new Basket<Apple> explicitly and copy fields from the Basket<Banana>.
What do people think about making the copy method generic for generic data classes?Joffrey
10/29/2025, 7:50 AMdata class Basket<F>(val fruits: Set<F>, val rottenFruits: Set<F>)
val bananas: Basket<Banana> = TODO("some basket of bananas")
val apples = bananas.copy(fruit = setOf(apple1, apple2)) // rottenFruits is not replaced here, so still bananas
By definition, copy is supposed to keep all other properties the same, so it wouldn't play nice with multiple generic properties.natpryce
10/29/2025, 7:55 AMJoffrey
10/29/2025, 7:58 AMnatpryce
10/29/2025, 9:01 AMJoffrey
10/29/2025, 9:03 AMcopy would be allowed to declare default values that disagree with the generic type parameter, and it would only be forbidden to use these default values by not providing arguments on the call site. That's not how other generic functions work, so it would be inconsistent unless we allow this for all generic functionsnatpryce
10/29/2025, 9:04 AMJoffrey
10/29/2025, 9:05 AMcopy (or `copy`s) to be defined for the Basket data class that I provided above?natpryce
10/29/2025, 9:06 AMnatpryce
10/29/2025, 9:14 AMdata class Basket<T> ... {
fun copy(fruit: Set<T>) = Basket(fruit,rottenFruit)
fun copy(rottenFruit: Set<T>) = Basket(fruit,rottenFruit)
fun <U> copy(fruit: Set<U>, rottenFruit: Set<U>) = Basket(fruit,rottenFruit)
}Joffrey
10/29/2025, 9:49 AMnatpryce
10/29/2025, 1:20 PMnatpryce
10/29/2025, 1:21 PMjoseph_ivie
10/30/2025, 2:38 PMJoffrey
10/30/2025, 3:22 PM