Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin interface constructor

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?

like image 499
Eerik Sven Puudist Avatar asked Mar 13 '26 22:03

Eerik Sven Puudist


1 Answers

Interfaces cannot have constructors in Kotlin.

Interfaces can have:

  • declarations of abstract methods
  • method implementations
  • abstract properties
  • properties which provide accessor implementations

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.

like image 93
Willi Mentzel Avatar answered Mar 15 '26 23:03

Willi Mentzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!