https://kotlinlang.org logo
#dsl
Title
# dsl
d

digitalsanctum

01/14/2019, 8:06 PM
Does anyone have an example project to share that has good constructs for Java (builders for Java, data classes for Kotlin). I'm wondering if the pattern is to just create builders in addition to data class constructors using named params, default values, etc.
s

snowe

01/14/2019, 10:49 PM
I can’t share a project, but I can share a snippet. Here’s a bit of our code to write builders for java, but just make regular calls from kotlin
Copy code
data class CalculationContext(
        val currencyUnit: CurrencyUnit,
        val roundingMode: RoundingMode,
        val ratioScale: Int
) {

    companion object {

        @JvmStatic fun builder() = CalculationContext.Builder()
        @JvmField val USA_STANDARD_CONTEXT = CalculationContext(CurrencyUnit.USD, RoundingMode.HALF_UP, 3)
        @JvmField val RATIO_CONTEXT =
                CalculationContext(CurrencyUnit.USD, BigDecimalUtilities.ROUNDING_MODE, BigDecimalUtilities.RATIO_SCALE)
        @JvmField val LTV_RATIO_CONTEXT = CalculationContext(CurrencyUnit.USD, RoundingMode.DOWN, 4)

    }

    class Builder {

        private var currencyUnit: CurrencyUnit = CurrencyUnit.USD
        private lateinit var roundingMode: RoundingMode
        private var ratioScale: Int = 0

        fun copyOf(v: CalculationContext) = apply {
            currencyUnit = v.currencyUnit
            roundingMode = v.roundingMode
            ratioScale = v.ratioScale
        }

        fun currencyUnit(v: CurrencyUnit) = apply { currencyUnit = v }
        fun roundingMode(v: RoundingMode) = apply { roundingMode = v }
        fun ratioScale(v: Int) = apply { ratioScale = v }

        fun build() = CalculationContext(currencyUnit, roundingMode, ratioScale)

    }

}
d

digitalsanctum

01/14/2019, 10:56 PM
@snowe thanks!
s

snowe

01/14/2019, 11:01 PM
we apply that pattern everywhere, since we still have several hundred thousand lines of java.