mvrx-mocking / com.airbnb.mvrx.mocking / DataClassSetDsl / set

set

open fun <DataClass : Any, Type> DataClass.set(block: DataClass.() -> KProperty0<Type>): DataClassSetDsl.Setter<DataClass, Type>

A small utility function to help copy kotlin data classes when changing a single property, especially where there is deep nesting. This is heavy on reflection, so isn't intended for high performance use cases.

This can only be called on Kotlin Data classes, and all nested objects that are modified must also be data classes.

data class DisclaimerInfo(val text: String)
data class BookingDetails(val num: Int = 7, val disclaimerInfo: DisclaimerInfo?)
data class State(val bookingDetails: BookingDetails)

val myState = State(BookingDetails(disclaimerInfo = DisclaimerInfo("text")))
// Using the helper utils we can update the nested text value like this
myState.set { ::bookingDetails { ::disclaimerInfo { ::text } } }.with { "hello world" }

// The standard way to set a nested value is much longer
myState.copy(
    bookingDetails = myState.bookingDetails.copy(
        disclaimerInfo = myState.bookingDetails.disclaimerInfo?.copy(
            text = "hello world"
        )
    )
)