Kotlin中的异步匿名函数? (lambdaexpression式)

我正在做一个列表查看什么时候点击调用函数。

I want to get function is async or sync

阻止什么时候是异步的。

甚至我想知道how attach async mark to kotlin lambda expression

 class FunctionCaller_Content(text: List, val function: List Unit )? >? = null) /* I want both of async, sync function. */ { fun isAsnyc(order: Int): Boolean = // how to get this lambda expression{function?.get(order)} is async? fun call(callerActivity: Activity, order: Int) { val fun = function?.get(order) fun() if(isAsync(fun)) /* block click for async func */ } } 

和用法。

 FunctionCaller_Content( listOf("Click to Toast1", "Click to Nothing"), listOf( { Toast.makeText(this, "clicked", Toast.LENGTH_SHORT) }, { /*if async lambda expression, how can i do?*/ } ) 

您可以使用List Unit> ,但除了使用List之外,您不能在同一个列表中同时使用挂起和非挂起function。 我建议使用两个单独的列表。 另一个解决方案是使用“代数数据types”:

 sealed class SyncOrAsync // can add methods here class Sync(val f: () -> Unit) : SyncOrAsync class Async(val f: suspend () -> Unit) : SyncOrAsync class FunctionCaller_Content(text: List, val function: List? = null) { fun call(callerActivity: Activity, order: Int) { val fun = function?.get(order) if(fun is Async) /* block click for async func */ } } FunctionCaller_Content( listOf("Click to Toast1", "Click to Nothing"), listOf(Sync { Toast.makeText(this, "clicked", Toast.LENGTH_SHORT) }, Async { // your async code }) 

但是,如果你只是要阻止,我会只使用List<() -> Unit>

 listOf({ Toast.makeText(this, "clicked", Toast.LENGTH_SHORT) }, { runBlocking { // your async code } })