如何为 Kotlin 中的构造函数隐式传递上下文

How to pass context Implicitly for constructors in Kotlin

我正在尝试根据定义它们的范围构建 class 的实例,而不使用显式参数。

这是从 Python 移植到 Kotlin 的一部分,但主要思想如下:

var d = MyClass()

use_scope(contextAForScope) {
    var a = MyClass()
    use_scope(contextBForScope) {
        var b=MyClass()
    }
}

在此示例中,d 构造函数将使用默认上下文,a 构造函数将使用 contextAForScopeb 构造函数将使用 contextBForScope (use_scope is这里只是一个占位符)。 像隐式上下文之类的东西?

当然,我可以使构造函数参数显式化,但这可能会在单个范围内多次使用,我不希望定义额外的变量。

with 就是你要找的:

class MyClass()

var d = MyClass()

fun main(args: Array<String>){
  var c = "c: Could be any class"
  var d = "d: Could be any class"

  with(c) {
    // c is "this"
    var a = MyClass()
    print(c) // prints "c: Could be any class"

    with(d) {
        // d is "this"
        var b = MyClass()
    }
    // b is undefined in this scope
  }
  // a is undefined in this scope
}

with 将 lambda 作为参数,该 lambda 中的所有内容仅在该范围内定义。

class MyClass(val context: Int)

fun MyClass() = MyClass(0)

interface MyClassScope {
    fun MyClass(): MyClass
}

object ContextAForScope : MyClassScope {
    override fun MyClass() = MyClass(1)
}

object ContextBForScope : MyClassScope {
    override fun MyClass() = MyClass(2)
}

inline fun useScope(scope: MyClassScope, block: MyClassScope.() -> Unit) {
    scope.block()
}

fun main(args: Array<String>) {
    val d = MyClass()

    useScope(ContextAForScope) {
        val a = MyClass()
        useScope(ContextBForScope) {
            val b = MyClass()
        }
    }
}

使用工厂函数创建您的 class。如果您将函数命名为 class,它看起来就像一个构造函数。

为范围定义一个具有相同工厂函数和两个对象的接口。

定义一个接受作用域和初始化程序块的函数。

现在您可以使用 useScope-Function 并在块内调用正确的工厂函数。