A bit of a language question: `data class` can't b...
# announcements
d
A bit of a language question:
data class
can't be extended (ok). If I chose to use an
interface
and implement it with a
data class
I can do things like this
Copy code
interface MyPublicInterface {
  val x: String
  val y: Int
  val z: Whatever
}

data class MyImplementation(
  override val x: String,
  override val y: Int,
  override val z: Whatever
): MyPublicInterface
now this is ok, but if I do this then I can't use the useful
copy()
or
componentN()
functions method that comes along with a data class on my interface without casting it to my implementation. Is there some way to make my interface declare the
copy()
and
componentN()
? for the
componentN()
I guess it's possible by just defining the operators, but then I'd had to manually maintain them, still ok. But for
copy()
I've no idea how to do it
PS: can you answer in a thread?
According to this: https://kotlinlang.org/docs/reference/data-classes.html
Copy code
Deriving a data class from a type that already has a copy(...) function with a matching signature is deprecated in Kotlin 1.2 and is prohibited in Kotlin 1.3.
do you know where i can find the discussion about this?
l
What is your use case here? Why do you need interfaces for data classes?
s
Alas, there is no such way; there are no such things as `data interface`s....
For a use-case: Imagine the 'data' interface having only a subset of the `val`s that its implementing
data
`class`es expose.
d
yes that's the use case
data class Sub
being a subset of the data in
data class Over
sharing the same interface matching Sub. or, as an alternative
data class A
and
data class B
sharing a subset of data that could be represented by an interface. An API returning the interface. In theory you could use
copy()
limited to the attributes of the common set and still create a valid
A
or
B
class.
I add a little bit... I'm currently doing something like this
Copy code
interface A
interface B
data class A_Data(...): A
data class B_Data(...): B

data class: X_Data(
  private val a: A,
  private val b: B
)A by a, B by b

where I manually expand this with a secondary constructor...

I'd love if I could let users of this X_Data class go and use it as if it was the sum of A_Data and B_Data.