spxbhuhb / z2-pre

Libraries for Kotlin Multiplatform development
Apache License 2.0
1 stars 0 forks source link

[Schematic] Create a constructor with parameters #6

Open toth-istvan-zoltan opened 10 months ago

toth-istvan-zoltan commented 10 months ago

Create a constructor that makes it possible to pass the field values directly.

Right now we have to set the field after the instance has been created:

Data().also {
    it.field = "hello"
}

There are two possible patterns to make the code above clearer:

Direct Constructor Parameters

In this case the compiler plugin generates a constructor with all fields.

Data(field = "hello")

Pros:

Cons:

Builder Function

In this case the compiler plugin adds a constructor that has a function parameter. This is equivalent to ().also { } but it is much more clean.

Data {
    field = "hello"
}

Pros:

Cons:

toth-istvan-zoltan commented 8 months ago

The constructor approach has to wait until IntelliJ 2024.2 as KMP + K2 won't be supported in 2024.1.

toth-istvan-zoltan commented 8 months ago

The builder function approach is already implemented. It needs adding the companion object manually but that's only because IDEA does not support K2 KMP yet.

For schematics with generics:

    companion object : SchematicCompanion<SelectField<Any,Any>> {
        @Suppress("UNCHECKED_CAST")
        @JvmName("genericInvoke")
        operator fun <VT,OT> invoke(builder : SelectField<VT,OT>.() -> Unit) : SelectField<VT,OT> =
            (newInstance() as SelectField<VT,OT>).apply(builder)
    }