12

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?

Michiel Leegwater
  • 1,172
  • 4
  • 11
  • 27
majkrzak
  • 1,332
  • 3
  • 14
  • 30

1 Answers1

28

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.

madhead
  • 31,729
  • 16
  • 153
  • 201