Is there a way to call a suspend function in `join...
# coroutines
v
Is there a way to call a suspend function in
joinToString
action while in a suspend function? Like this (https://pl.kotl.in/7ydf0wXCo):
Copy code
suspend fun main() {
    println(listOf("").joinToString { foo() })
}

suspend fun foo() = "foo"
Of course that version does not work and is majorly oversimplified example. But how would one get this working properly?
j
It would be possible if
joinToString
were
inline
, but it is apparently not. So I guess you would have to write your own inline version of it
r
You can just
.map {}
before calling
joinToString
. I think the result will be the same.
💯 1
v
Ah, I did try, but I tried with
Copy code
suspend fun main() {
    println(listOf("").map(Any::foo).joinToString())
}

suspend fun Any.foo() = "foo"
When I instead do
Copy code
suspend fun main() {
    println(listOf("").map { it.foo() }.joinToString())
}

suspend fun Any.foo() = "foo"
it works. Why is the latter working, but the former not?
t
map takes a transformer to type
(T) -> R
, but
Any::foo
is of type
KSuspendFunction
so its a type mismatch.
.map { it.foo() }
make a higher order function of type
(T) -> R
v
Ah, thanks, that works then in my case.
y
What I've done before is copy `joinToString``s source code and make it inline. I understand why they didn't make it inline, but they really should. Also, the reference vs lambda thing with
suspend
is a long standing issue. I think I saw something on YouTrack suggesting that they'll improve this, but I can't remember
v
Thanks, using
map
is fine for me.
➕ 1
Hm, how about inside
sequence { ... }
? So like
Copy code
suspend fun main() {
    println(sequence { yield(foo()) }.joinToString())
}

suspend fun foo() = "foo"
which complains with
Restricted suspending functions can invoke member or extension suspending functions only on their restricted coroutine scope.
y
Turn it to list, map, then joinToString... which is annoying, I agree. You can also use
flow
instead of
sequence
.
v
Ah, yes,
flow
works, thanks
y
In general,
flow
is a `suspend`ing
sequence
. It's technically slightly slower (I think), since
sequence
benefits by only `suspend`ing on
yield