hi guys! just a question, does instantiating (Clas...
# dsl
y
hi guys! just a question, does instantiating (ClassName()) act as an invoke, or can I add functionality to instantiating in some other way? currently have a function add that takes in a Component, though this looks rather bad. can I automatically call add on every instantiated object in my dsl? thanks!
m
You can put some logic in the
init
block:
Copy code
class Foo(arg: String) {
  init {
    println("Hello, $arg")
  }
}
Another way would be to make the constructor private and create a function instead:
Copy code
class Foo private constructor() {
  companion object {
    operator fun invoke(arg: String): Foo {
      println("Hello, $arg")
      return Foo()
    }
  }
}
Or, yet another way of doing it:
Copy code
private class Foo : IFoo

fun Foo(arg: String): IFoo {
  println("Hello, $arg")
  return Foo()
}
v
you can add
fun ClassName() { ... }
y
the logic isnt handled by the class but by my dsl builder, so I want the builder’s add function to get called every time I make a new object, init/constructor wont work cuz that doesnt know who built it
@vladimirsitnikov I already have functions for these, but I want to be able to create new ones without having to change the builder
v
Could you add samples of what you are trying to achieve?
y
Copy code
class MyUI : UI() {
    override fun build(): Component {
        root {
            add(VStack {
                add(Button(“click”))
            })
        }
    }
}
this is my current setup, but I want to remove the
add
calls which looks redundant edit: with VStack and Button both being classes extending Component, and root func creating a top level parent Component
m
Not quite sure how
add
is defined for you, but assuming it's a function like this:
Copy code
interface UiBuilder {
  fun add(...)
}
You could use extension functions:
Copy code
fun UiBuilder.VStack(builder: VStackUiBuilder.() -> Unit) { add(...) }