I'm coming from Java and am new to Kotlin. I am trying to create declarative DSL for unit testing purposes. Here is my attempt to create generic builder method to construct any model object with declarative syntax.
fun <T> having(t: Class<T>) = object {
infix fun with(fn: T.() -> Unit) = t.newInstance().apply(fn)
}
fun test() {
having(Pizza::class.java) with {
size = Size.NORMAL
cheese = Cheese.MOZARELLA
}
}
However, the having function returns Any type with unresolved reference to with function. I could extract the anonymous object to it's own class to make it compile, but it would feel redundant. Is it possible to resort on the type inference with functions returning an object instances?
Also, I'm not sure if I'm using generics the idiomatic way here.