https://kotlinlang.org logo
Title
p

pepe

08/21/2019, 11:04 AM
hey! I'm trying to write a generic function to set a default value on a nullable property of an immutable object and I have two obstacles: - can I constraint a type so it is a data class (implements a copy constructor)? - can I address the right property in the copy constructor using the KProperty? This is what I have so far:
fun <T: ???, R> T.setDefault(prop: KProperty1<T, R>, defaultValue: R): T =
        prop.get(this)?.let { this } ?: copy(??? = defaultValue)
P.S. maybe this I'm trying to do is stupid/not worth it, feel free to point it out
m

Mike

08/21/2019, 11:43 AM
I assume the default can't be defined on the data class definition itself?
r

Ruckus

08/21/2019, 1:39 PM
Data classes do not define a copy constructor, only a copy function, and the generated copy functions for different classes are not guarunteed to have the same signature. There's nothing (from a definition/signature standpoint) that is common among all data classes, so restricting to data classes isn't possible (and wouldn't be useful if it was possible).
👍 1
data
is a compiler code generation feature. At runtime, there is nothing special about data classes.
p

pepe

08/23/2019, 9:48 AM
I understand, thanks, so there's no way to make this generic, right?