在 Kotlin 中,我希望有一个接口(interface),它坚持实现类具有特定的构造函数。像这样的东西:
interface Inter<T> {
// Must have constructor (t: T)
}
class Impl(t: String): Inter<String>
如何做到这一点?
最佳答案
接口(interface)在 Kotlin 中不能有构造函数。
接口(interface) can have :
最接近您想要实现的目标是使用抽象类或普通类:
abstract class Foo<T>(val t: T)
class Bar<T>(t: T): Foo<T>(t)
请注意,
Bar
必须调用 Foo
的主构造函数,但它不必暴露它。abstract class Foo<T>(val t: T)
class Bar: Foo<String>("Hello")
所以,这是完全有效的:
Bar()
如您所见,您实际上不能坚持实现类具有特定的构造函数。
关于generics - Kotlin 接口(interface)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56409640/