在 Kotlin 中,如何委托给接口并仅提供无参数 public 构造函数?
In Kotlin, how to delegate to an interface and provide only a no-arg public constructor?
问题出在 Kotlin class delegation 只允许委托给构造函数参数,因此似乎迫使您为构造函数提供一个参数。
下面是我的原始问题,是关于这个问题的具体用例。
我想执行以下操作:
val myTable1: MyTable = MyTable()
其中
MyTable
继承自 ImmutableTable (src) or at least Table
- 而且我不必手动将所有
Table
方法委托给某些基本实现。
我还想避免以下情况:
val myTable2: MyTable = MyTable.build()
即我不想被迫使用伴随对象/静态工厂方法。
我试图扩展 ImmutableTable
,但我得到 This type has a constructor, and thus must be initialized here
。
我试图扩展 Table
接口并委托给它(以避免重新实现方法)但后来我被迫提供 Table
的实例作为构造函数参数。我不能只在 init {}
块中初始化它。
请参阅 this gist 了解我的确切尝试。
使用的 Kotlin 版本:1.0.2
正如评论中提到的,Guava ForwardingTable
可以做到这一点。但是这里有另一个选项,即使对于没有定义 "forwarding" 版本的接口也应该有效。
class MyTable private constructor(table: Table<Int, Int, Int>) : Table<Int, Int, Int> by table {
constructor() : this(TreeBasedTable.create()) // or a different type of table if desired
}
问题出在 Kotlin class delegation 只允许委托给构造函数参数,因此似乎迫使您为构造函数提供一个参数。
下面是我的原始问题,是关于这个问题的具体用例。
我想执行以下操作:
val myTable1: MyTable = MyTable()
其中
MyTable
继承自 ImmutableTable (src) or at least Table- 而且我不必手动将所有
Table
方法委托给某些基本实现。
我还想避免以下情况:
val myTable2: MyTable = MyTable.build()
即我不想被迫使用伴随对象/静态工厂方法。
我试图扩展 ImmutableTable
,但我得到 This type has a constructor, and thus must be initialized here
。
我试图扩展 Table
接口并委托给它(以避免重新实现方法)但后来我被迫提供 Table
的实例作为构造函数参数。我不能只在 init {}
块中初始化它。
请参阅 this gist 了解我的确切尝试。
使用的 Kotlin 版本:1.0.2
正如评论中提到的,Guava ForwardingTable
可以做到这一点。但是这里有另一个选项,即使对于没有定义 "forwarding" 版本的接口也应该有效。
class MyTable private constructor(table: Table<Int, Int, Int>) : Table<Int, Int, Int> by table {
constructor() : this(TreeBasedTable.create()) // or a different type of table if desired
}