Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 理解kotlin遗嘱执行人_Java_Kotlin_Executor - Fatal编程技术网

Java 理解kotlin遗嘱执行人

Java 理解kotlin遗嘱执行人,java,kotlin,executor,Java,Kotlin,Executor,我理解遗嘱执行人的概念,但我在理解kotlin的遗嘱执行人时遇到了一些困难。也许是语法没有帮助 让我们看看下面的例子: private class AlwaysCallback(private val executor: (() -> Unit) -> Unit, private val cb: Progress.() -> Unit) : Callback { override f

我理解遗嘱执行人的概念,但我在理解kotlin的遗嘱执行人时遇到了一些困难。也许是语法没有帮助

让我们看看下面的例子:

     private class AlwaysCallback(private val executor: (() -> Unit) -> Unit,
                                  private val cb: Progress.() -> Unit) : Callback {
         override fun execute(progress: Progress) {
             executor {
                 progress.cb()
             }
         }
     }
如果我理解正确的话,执行者
(()->Unit)->Unit
是用于关闭的容器。要执行的代码块。我不确定这是真的还是它只是一个匿名函数的容器

另一件事是,有人能解释一下语法:
(()->Unit)->Unit

我已经阅读了kotlin文档,阅读了kotlin源代码,并尝试用谷歌搜索它,但我真的很难理解这一点。谢谢

()->Unit
是一个函数,它不以任何内容作为参数,也不返回任何内容。例如,
Runnable.run()
就是这样一个函数。您可以将此函数视为任务

所以,
(()->Unit)->Unit
是一个函数,它接受这样一个函数作为参数,并且不返回任何内容。例如,
Executor.execute(Runnable)
就是这样一个函数。因此,它是一个以任务为参数的函数(很可能是现在、以后、一次或多次执行该任务)

下面是一个示例,它定义了一个创建我刚才称之为任务的函数,以及另一个返回执行器的函数,即执行任务的函数:

fun createTask(): () -> Unit {
    return {
        println("Hello world")
    }
}

fun createExecutor() : (() -> Unit) -> Unit {
    return { task: () -> Unit ->
        println("I'm going to execute the task...")
        task()
        println("I'm going to execute the task a second time...")
        task()
    }
}

fun main(args: Array<String>) {
    val task = createTask()
    val executor = createExecutor()
    executor(task)
}
fun createTask():()->单位{
返回{
println(“你好,世界”)
}
}
fun createExecutor():(()->Unit)->Unit{
返回{task:()->Unit->
println(“我将执行任务…”)
任务()
println(“我将再次执行任务…”)
任务()
}
}
趣味主线(args:Array){
val task=createTask()
val executor=createExecutor()
执行人(任务)
}

请注意,我自己仍在学习Kotlin,因此我仍在努力学习语法和概念。

Unit在这里解释:。我阅读了Unit keywork的文档。我现在明白了。您的示例相当好,但是,当我尝试想象时,我仍然有点挣扎,但是使用参数和/或返回值。另一件事,
createTask()
是否返回闭包?是的。但我认为合适的Kotlin术语是“函数文字”,也就是lambda表达式。如果它“捕获”了一个在函数文本之前定义的局部变量,那么它将真正成为一个闭包,这里不是这种情况。对不起,但是您试图实现的是什么?你能解释一下或给出一个有效的Java代码吗?