hispanicprogrammer
hispanicprogrammer

Reputation: 437

How to initialize nested data class in Kotlin?

I have the following structure in a data class:

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

    data class C(
        val d: Int
    )  
}

and an instance of this class is being passed to a method which has the following signarure:

fun doSomethingMethod(object: A.B?): Mono<Unit> =
            // do something
            }

So now I am trying to initialize an instance of the data class A with only initializing B as wel but I dont understand how to do it. So far I have tried:

val testObject = A(A.B(5))

But its not working. Anyone has an idea?

Upvotes: 2

Views: 2004

Answers (1)

Sergio
Sergio

Reputation: 30635

To create an object of nested data class just use next syntax:

val instance = OuterClass.NestedClass([params])

In your case it will be:

val b = A.B(5)

Complete example:

fun doSomethingMethod(b: A.B?): Mono<Unit> {
    // do something
}

val b = A.B(5)
val mono = doSomethingMethod(b)

Upvotes: 4

Related Questions