Hey all, I'm not really understanding how to harne...
# announcements
a
Hey all, I'm not really understanding how to harness the full power of trailing lambdas, I'm fairly certain it's what I want but I'm also open to being wrong. I am fairly Inexperienced with Kotlin so please take me to school if you need to! I am trying to mimic behaviour that I noticed in Ktor's HTTP Client when it comes to applying the
body
parameter, but in my own abstraction of a client for a particular service endpoint. Basically, I have this function (fluff removed), but point is clear.
Copy code
sendNotification(listOf("..."), listOf("..."))
This is ultimately fine and works as intended, but I am trying to find a way to explicitly set each of these values. Instead I'd like to do this:
Copy code
sendNotification() {
    subscriberKeys = listOf("...")
    users = listOf("...")
}
This helps me describe exactly what I need each value to be and then pass them through the implementation, I just don't fundamentally understand the examples provided. I've tried with some smaller sample code but nothing quite clicks yet. I'll gladly accept links to helpful resources too, I've done a fair amount of searching but nothing has quite illuminated the lightbulb on this.
s
1) you should keep most of this in a thread instead of filling the channel, 2) do you really need trailing closures for what you’re trying to do? Have you tried keyword arguments?
Copy code
sendNotification(
    subscriberKeys = listOf(...),
    users = listOf(...),
)
2
I realize this doesn’t exactly answer your question as originally stated—here are some docs on Type-safe builders that should address what you want to learn about https://kotlinlang.org/docs/type-safe-builders.html https://kotlinlang.org/docs/lambdas.html#function-literals-with-receiver
a
Totally fair didn't mean to take up as much space as it did, just wanted to be clear on my initial vision. I actually had no idea that keyword arguments worked that way, taking a look at how it works that's more than enough to get the point across.
💯 2
s
No worries dude, just something to keep in mind for next time
n
"trailing lambda" is really just syntactic sugar: given a function
fun foo(body: () -> Unit)
, you can call this with
foo { ... }
instead of
foo({ ... })
by applying 2 rules: (1): if the last argument of a function is a lambda, you can move that out of the
()
when calling the function and (2) if you call a function using "trailing lambda" and that function needs no other parameters than the lambda, you can omit the
()