Hey all I'm trying to learn Kotlin by experimentin...
# getting-started
j
Hey all I'm trying to learn Kotlin by experimenting after finishing the koans. I'm trying to add some syntactic sugar to Amazon's CDK (for building CloudFormation templates) using Kotlin, but I'm having problem with generics and a function literal receiver that's a lot like
apply
. What I want to accomplish is being able to write:
buildProps(VpcNetworkProps.Builder()) { withCidr("10.0.0.0/8") }
where
buildProps
, above, would return
VpcNetworkProps
by calling the builder's build() method after applying the block. The problem I'm having is that the CDK doesn't have any interfaces or parent types for its Builder classes even though they're all the same. If I had an interface to latch onto, the following would probably work, but I don't have :
Copy code
// My pretend interface that CDK doesn't provide.
// Can I somehow endow the builders this interface without modifying the vendor's code?
interface PropBuilder<P> {
    fun build(): P
}

fun <P>buildProps(propBuilder: PropBuilder<P>, block: PropBuilder<P>.() -> Unit): P =
    with(propBuilder) {
        block()
        build() // P
    }