I’m still learning generics in general, trying to ...
# announcements
j
I’m still learning generics in general, trying to implement a generic builder pattern for the type safe builder approach. I currently have… `
Copy code
fun <T> screen(init: T.() -> Unit): T = init as T
Then eventually extend it have bounds, but for now. I keep getting a casting error. I’m assuming because it’s not invoking init, but I can’t seem to figure that part out.
essentially, I will have a class call this function like: `
Copy code
fun class(init: MainView.() -> Unit) = screen(init)
It appears to work as:
Copy code
fun <T> screen(obj: T, init: T.() -> Unit): T {
    obj.init()
    return obj
}
then invoking with
Copy code
fun(view: MainView.()-> Unit) = screen(MainView(), view)
simply because I’m sending in the object. Is there a better approach so I don’t have to explicitly send in the
MainView()
to the generic builder?
You'll want to invoke screen with a closure. So either
screen { /* code here */ }
or
screen(MainView()) {/* code here */ }
The reference has examples of both.. You can also look at the buildString source code.
j
Thank you!