Adrián
05/27/2019, 1:40 PMsealed class MyModel {
abstract val name: String
abstract val title: String
}
data class Model1(
override val name: String,
override val title: String,
) : MyModel()
...
data class Model100(
override val name: String,
override val title: String,
) : MyModel()
If you want to modify the title, for example, adding the environment where you are running your code could be similar to: fun MyModel.addEnvironmentToTitle(env: String) = when (this) {
is MyModel1 -> copy(title = title + env)
... -> // Same boilerplate here
is MyModel100 -> copy(title = title + env)
}
It is a simple example but you could have more complex code and it becomes unmanageable.
Does anyone know if we will have in the future an option to restrict Sealed classes implementation to Data classes? With that restriction previous method would be: fun MyModel.addEnvironmentToTitle(env: String) = copy(title = title + env)Dico
05/27/2019, 2:03 PMtitle as a property on the common class. That's what inheritance is for.streetsofboston
05/27/2019, 2:07 PMcopy method.streetsofboston
05/27/2019, 2:08 PMLawik
05/27/2019, 2:21 PMinline fun <reified T: MyModel> T.addEnvironmentToTitle(env: String): T = when {
T::class.isData -> T::class.memberFunctions.first{ it.name == "copy"}.call(this, this.title, this.title + env) as T
else -> this
}Adrián
05/27/2019, 2:31 PMAdrián
05/27/2019, 2:32 PMAdrián
05/27/2019, 2:34 PMstreetsofboston
05/27/2019, 2:35 PMcomponentXXX methods as well.stevecstian
05/27/2019, 4:18 PMcopy in MyModel due to https://kotlinlang.org/docs/reference/compatibility-guide-13.html#data-class-overriding-copy , but we can have a copy-like abstract fun in MyModel.Adrián
05/27/2019, 5:52 PMRuckus
05/28/2019, 2:45 PMcopy function. The generated function will have the same signature as the constructor, it just conveniently defines defaults for you. As a result, it makes no sense to require classes to be data as there is no common code among data classes.