如何传递上下文隐含在Kotlin中的构造函数

我试图根据定义的范围来构造一个类的实例,而不使用显式参数。

这是从Python到Kotlin的一个端口的一部分,但主要想法是这样的:

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

在这个例子中, d构造函数使用默认上下文,构造函数使用contextAForScopeb构造函数使用contextBForScope (use_scope只是一个占位符) 。 像隐式的上下文?

当然,我可以使构造函数参数显式化,但这可能会在单个作用域中使用多次,我不想定义一个额外的variables。

 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) { val d = MyClass() useScope(ContextAForScope) { val a = MyClass() useScope(ContextBForScope) { val b = MyClass() } } } 

使用工厂function来创建你的class级。 如果你像这个类一样命名这个函数,它就像一个构造函数。

定义一个具有相同工厂函数的接口和两个作用域的对象。

定义一个接受范围和初始化块的函数。

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

with您正在寻找的是:

 class MyClass() var d = MyClass() fun main(args: Array){ 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中的所有内容都只在该范围内定义。