How to create a builder for a Kotlin data class with many immutable properties

I have a Kotlin data class that I am building with many immutable properties that are extracted from individual SQL queries. If I want to build a data class using the builder template, how can I do this without changing these properties?

For example, instead of building through

var data = MyData(val1, val2, val3)

I want to use

builder.someVal(val1)
// compute val2
builder.someOtherVal(val2)
// ... 
var data = builder.build()

still using the Kotlin data class function and immutable properties.

+4
source share
4 answers

I do not think that Kotlin has native builders. You can always calculate all values ​​and create an object at the end.

, .

+3

Grzegorz, , . , , , .

, :

,

data class Data(val text: String, val number: Int, val time: Long)

, , :

class Builder {
    var text = "hello"
    var number = 2
    var time = System.currentTimeMillis()

    internal fun build()
            = Data(text, number, time)

}

:

fun createData(action: Builder.() -> Unit): Data {
    val builder = Builder()
    builder.action()
    return builder.build()
}

- , , createData . , :

val data: Data = createData {
    //execute stuff here
    text = "new text"
    //calculate number
    number = -1
    //calculate time
    time = 222L
}

, .

kotlin get set, , , .

, .

: , createData :

fun createData(action: Builder.() -> Unit): Data = with(Builder()) { action(); build() }.

" "

+3

Kotlin - copy - , .

data class MyData(val val1: String? = null, val val2: String? = null, val val3: String? = null)

val temp = MyData()
  .copy(val1 = "1")
  .copy(val2 = "2")
  .copy(val3 = "3")

:

val empty = MyData()
val with1 = empty.copy(val1 = "1")
val with2 = with1.copy(val2 = "2")
val with3 = with2.copy(val3 = "3")

, , .

, , , , , .

+1

- .   ephemient/builder-generator, .

Note that kapt currently works fine for generated Java code, but there are some problems with generated Kotlin code (see KT-14070 ). For these purposes, this is not a problem if zero-probability annotations are copied from Kotlin source classes to generated Java -collectors (so Kotlin code using generated Java code sees types with zero / non-empty value, and not just with the type platform).

+1
source

Source: https://habr.com/ru/post/1683114/


All Articles