Dan T
05/29/2019, 8:25 PMsealed class Animal {
abstract val weight: Int
}
data class Dog(
override val weight: Int,
private val barkSound: String
) : Animal()
data class Cat(
override val weight: Int,
private val meowSound: String
) : Animal()
fun main() {
val dog : Animal = Dog(weight = 1, barkSound = "woof")
// what's the most elegant way to allow the following?
val heavierDog = dog.copy(weight = weight + 1)
}
sealed class Animal {
abstract val weight: Int
abstract fun copy(
weight: Int = this.weight
): Animal
}
data class Dog(
override val weight: Int,
private val barkSound: String
) : Animal() {
override fun copy(weight: Int): Animal {
return copy(weight = weight, barkSound = this.barkSound)
}
}
data class Cat(
override val weight: Int,
private val meowSound: String
) : Animal() {
override fun copy(weight: Int): Animal {
return copy(weight = weight, meowSound = this.meowSound)
}
}
fun main() {
val dog : Animal = Dog(weight = 1, barkSound = "woof")
val heavierDog = dog.copy(weight = 2)
println(heavierDog)
}
karelpeeters
05/29/2019, 8:37 PMDan T
05/29/2019, 8:52 PMsealed class Animal {
abstract val weight: Int
abstract fun copy(
weight: Int = this.weight
): Animal
}
data class BasicAnimal(
override val weight: Int
) : Animal()
karelpeeters
05/29/2019, 8:52 PMclone
😒imple_smile:Dan T
05/29/2019, 8:53 PMFunction 'copy' generated for the data class has default values for parameters, and conflicts with member of supertype 'Animal'
karelpeeters
05/29/2019, 8:55 PMcopy
function for data classes was a mistake.Dan T
05/29/2019, 9:07 PMstreetsofboston
05/29/2019, 9:59 PMgildor
05/29/2019, 11:31 PMkarelpeeters
05/29/2019, 11:39 PMcopy
• "Private data class constructor is exposed via the generated copy
method", this basically makes private data class constructors useless.gildor
05/29/2019, 11:55 PMcopy
and keep using AutoValue or similar solution
2. Not really a big problem, imo, but would be nice to fix
3. I agree that it is unfortunate, would be nice to have a way to make copy private or disable itkarelpeeters
05/30/2019, 12:05 AMhashcode
and equals
make sense, component
a bit less and copy
even less. Some modularity would be nice but then that's more syntax. It's a balance 😒imple_smile:gildor
05/30/2019, 12:40 AMDico
05/30/2019, 2:18 AMkarelpeeters
05/30/2019, 8:58 AMgildor
05/30/2019, 9:33 AMkarelpeeters
05/30/2019, 10:33 AMequals
and hashcode
to be generated.Dico
05/30/2019, 1:40 PMkarelpeeters
05/30/2019, 1:41 PMDico
05/30/2019, 1:43 PMkarelpeeters
05/30/2019, 1:44 PMDico
05/30/2019, 1:44 PMkarelpeeters
05/30/2019, 1:45 PMearroyoron
05/31/2019, 9:21 PMcopy
is perfect for data class
as a data class is something you should not extend. Don’t worry to duplicate properties in two `data class`es as this is just where DRY is not applicable