Hi all, I want to define a kotlin function as a pa...
# announcements
l
Hi all, I want to define a kotlin function as a parameter for a class and I want that kotlin function to be able to have 0 or more arguments. Is there a way to do that? Ex:
Copy code
class Builder (
private val function: (suspend () -> String) //Don't want to force Builder to have to provide a no argument function
)
Context: I used to be able to do this in RxJava with a Single. Moving to Coroutines / Flow.
v
How will you call
function
if you don't know how many arguments it will have?
l
good point, but we use
vararg
in other functions...
Good point. What I guess I really want is to provide a function (with no args)
and be able to pass a function that took in args?
Ex:
Copy code
val builder = Builder(::exampleFunc)
func exampleFunc(x: Int): String {...}
v
Same question with that example, who will provide the argument given to
x
?
Surely not the builder, as it should not even know how many arguments are there, let alone give arguments for them
l
caller of builder?
v
At what place?
l
Yeah builder doesn't care on number of arguments, it just wants to invoke the suspend function and get a result
v
So maybe you mean like that:
Copy code
class Builder(
        private val function: suspend () -> String
)

fun exampleFunc(x: Int): String = ""
val builder = Builder { exampleFunc(1) }
You give it a function that calls your function with the parameters you want
l
oh ok thank you!
v
yw
y
If you will always make sure that only the caller of builder calls the method, then you can do something like this:
Copy code
class Builder<R, T: KFunction<R>>(private val func: T) {
    inline fun callFunction(caller: T.() -> R) = func.caller()
}