Concise way to define a suspending lamba?

#1

Hello,
My code looks like:

	fun f() {
		val l = { x: Long ->
			println(x)
		}
		l(10)
	}

I really like not having to explicitly specify types in Kotlin in most cases, e.g. in this case I didn’t have to specify l's type explicitly.

However, this doesn’t work for suspending functions:

	suspend fun f() {
		val l = { x: Long ->
			delay(x)
		}
		l(10)
	}

This does not compile, because unfortunately compiler can’t deduce that l should be suspending. The only way I can make it work is:

	suspend fun f() {
		val l: suspend (Long) -> Unit = { x: Long ->
			delay(x)
		}
		l(10)
	}

But this is really cumbersome, especially with >1 arguments. Does anyone know a shorter way? Would it make sense to have the compiler automatically deduce l is suspending iff I used any suspending function inside of it?

Thanks!

#2

i don’t like the idea to automatically make it a suspension-function.
If I accidentally call a custom function that appears to be a suspension-function, I want an error instead of making the entire lambda suspending.

An idea could be to create another function:

fun <T> suspenFun(func: suspend (T) -> Unit) = func

then the code would become:

suspend fun f() {
	val l = suspenFun{ x: Long ->
		delay(x)
	}
	l(10)
}

Which is way less inflexible, but it’s the way I build extension-lambda’s…

#3

Would it be possible to allow suspend keyword in this context?

suspend fun f() {
	val l = suspend { x: Long ->
		delay(x)
	}
	l(10)
}

But I have to say I don’t see an argument against auto-deducing. If you were to use l elsewhere where suspend is not expected, you will get a compiler error later on (e.g. you try to pass it as parameter). If you were to use it where suspend is expected, in that case compiler was right.

Suspending and non-suspending functions can never be mixed.

#4

Take a look here

https://youtrack.jetbrains.com/issue/KT-22766

https://youtrack.jetbrains.com/issue/KT-22765

1 Like
#5

Seems related! :partying_face: