gpt4 book ai didi

不在范围内的 Kotlin 变量?

转载 作者:行者123 更新时间:2023-12-04 01:01:08 38 4
gpt4 key购买 nike

关于 https://github.com/mozilla/rust-android-gradle/blob/8183f9e927336011c7c09d75efd4f5f411940db1/plugin/src/main/kotlin/com/nishtahir/CargoBuildTask.kt#L19我们有这个 Kotlin 代码:

open class CargoBuildTask : DefaultTask() {
var toolchain: Toolchain? = null


@Suppress("unused")
@TaskAction
fun build() = with(project) {
extensions[CargoExtension::class].apply {

我很困惑extensionsproject 是从哪里来的。它们不是局部变量,它们不在范围之内。它们是什么?

最佳答案

Inheritanceproject 的答案。

CargoBuildTask : DefaultTask()

你看到 CargoBuildTask 是如何继承 DefaultTask 的属性了吗?因此 projectDefaultTask 的属性。但是,extensionsproject 的属性,类型为 Project

Read this documentation on DefaultTask and you will have more understanding.

Kotlin 的with扩展 的答案。

简而言之,使用with,您可以在不显式声明其主题的情况下调用方法。 ( Read more here )

例如,这两个代码片段的含义完全相同:

    with("string") {
substring(3) //invoke method without subject
}

"string".substring(3) //Same as above

这是来自 org.gradle.api.Project 的方法

   ExtensionContainer getExtensions();

现在,如果您想知道 Java 的 getExtensions() 是如何变成 Kotlin 的 extensions 的,read this .基本上指出,Java 中的传统 Getter 和 Setters 在 Kotlin 中被解释为 Properties

PS:如果您不确定 OOP/Kotlin 中的Inheritance 是什么,read this .

关于不在范围内的 Kotlin 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68190067/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com