ReadWrite.forEachLine with suspending action not compiling

I have a BufferedReader that I want to use to perform a suspending action on reading each line.

fileReader.useLines { it.forEach { someSuspendFunction() } }

compiles, whereas the more succinct but nearly identical

fileReader.forEachLine { someSuspendFunction() }

does not compile. I get the error “Suspension functions can be called only within coroutine body”

I think it should be fine given that the definition of “forEachLine” is simply:

useLines { it.forEach(action) }

Am I missing some reason why this code should not compile? Or is there a bug where forEachLine should really be an inline function, or something?

1 Like

We decided that forEachLine should not be an inline function due to a large amount of bytecode it would have produced on the call site, be it inline.

Thanks, Ilya. Is that the reason that forEachLine cannot be used with suspending functions, then? Or was I missing something?

Yes, suspending inside a non-suspend lambda function is only possible in a lambda that is inlined into another suspend function.

1 Like