Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to nest dataclass in kotlin?

I'm trying to achieve similar data class definition like the following C one:

struct A {
  int b;
  struct {
     int d;
  } c; 
};

According to Dmitry Jemerov it is possible, but he didn't provide any code sample. https://discuss.kotlinlang.org/t/is-there-a-reason-for-not-allowing-inner-data-classes/2526/5

You can simply make it nested inside another class. Nested classes can be data classes.

How it should be done if it is true?

like image 944
majkrzak Avatar asked Oct 07 '19 16:10

majkrzak


1 Answers

No, Kotlin does not support anonymous structures like that.

You can both literally nest the classes:

data class A(
    val b: Int,
    val c: C
) {
    data class C(
        val d: Int
    )
}

Or use a more common syntax:

data class C(
    val d: Int
)

data class A(
    val b: Int,
    val c: C
)

Actually, there is no need in "nesting" here. The difference will be mostly in the way you access the C class: A.C or just C.

like image 109
madhead - StandWithUkraine Avatar answered Nov 04 '22 23:11

madhead - StandWithUkraine