How can I get a parameter value in this function?

fun text(text: String, do: () -> Unit) {
  println(text)
  do()
}

The usage:

text(
  text = "1",
  do = { *** }
)

But how can I get parameter text (“1”) in *** ?

Creating a variable at the top? I didn’t prefer that. Because there are lots of text() in my project.

You could pass it to the lambda.

fun text(text: String, do:  (String) -> Unit) {
    println(text)
    do(text)
}
text("1") { text ->
    println(text)
}
text("2")  {
    println(it)
}
2 Likes

Add a text parameter in your lambda parameter like this: fun text(text: String, do: (String) -> Unit)

Then in your function body, pass in text like this: do(text)
Then whenever you call the text function, you have access to the text parameter in the lambda body (i.e. by referring to it as it or naming it directly like this: text("1") { input -> ***}

1 Like

Missed a typo there dude lol. It should be (String) -> Unit

1 Like

Yeah my computer is kinda broken. I definetly need to get a new one. It randomly repeats characters I typed up to a second ago.

1 Like

Thank you :slight_smile:. It’s really a good solution.

1 Like