10

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?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Eerik Sven Puudist
  • 2,098
  • 2
  • 23
  • 42
  • 2
    You can't do that. Interfaces only define required methods. What you're looking for is probably an `abstract class`. – Pawel Jun 01 '19 at 19:50
  • 4
    As @Pawel says, this isn't possible in Kotlin. (Probably because it's not possible in Java; see answers like https://stackoverflow.com/questions/3164334 and https://stackoverflow.com/questions/6028526.)  In fact, it's not even possible in an abstract class, which can require its subclasses to call its constructor, but can't impose any conditions on what constructors its subclasses choose to expose.  The usual workaround is just a convention spelled out in the doc (e.g. for collection classes to have a copy-constructor). – gidds Jun 01 '19 at 21:03

1 Answers1

11

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.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121