Reputation: 2348
In Kotlin I would like to have an interface that insists the implementing class to have a certain constructor. Something like this:
interface Inter<T> {
// Must have constructor (t: T)
}
class Impl(t: String): Inter<String>
How to achieve this?
Upvotes: 12
Views: 18206
Reputation: 29844
Interfaces cannot have constructors in Kotlin.
Interfaces can have:
The closest you can get to what you want to achieve is to use an abstract class or a plain class:
abstract class Foo<T>(val t: T)
class Bar<T>(t: T): Foo<T>(t)
Note, that Bar
has to call the primary constructor of Foo
, but it does not have to expose it.
abstract class Foo<T>(val t: T)
class Bar: Foo<String>("Hello")
So, this is completely valid:
Bar()
As you see, you cannot actually insist that the implementing class has a certain constructor.
Upvotes: 13