Kotlin
Interfaces
Programming
Software Development
Object-Oriented Programming

Kotlin Interface ... does not have constructors

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Understanding Kotlin's Interface: The Constructor Limitation

Kotlin, a modern programming language, introduces several enhancements over traditional Java programming. One fundamental concept that Kotlin borrows from Java but modifies with added functionality, is the use of interfaces. A commonly puzzling aspect when transitioning from class-based to interface-based design in Kotlin is the statement: "Interface ... does not have constructors." In this article, we will dissect this concept, analyze its implications in Kotlin, and provide practical examples. Here’s a detailed technical journey into why interfaces don’t have constructors and how you can work around this.

Why Interfaces Don't Have Constructors

1. Conceptual Purpose:

An interface in Kotlin, like in Java, acts as a contract. It defines a set of methods but does not provide the implementation. The key purpose is to define capabilities that a class should implement. Constructors, on the other hand, are mechanisms to instantiate classes. Since interfaces merely define contracts and do not deal with instantiation, they inherently do not possess constructors.

2. Design Implications:

Allowing interfaces to have constructors would mean allowing them to acquire state, which is inconsistent with the expectation that an interface should only declare behavior. If interfaces had constructors, they would start resembling abstract classes, thus blurring the design boundaries.

3. Language Consistency:

Kotlin is designed to support object-oriented programming with clear distinctions between classes and interfaces. Enabling constructors within interfaces could potentially derail this structured separation, leading to complexity and ambiguity in inheritance and object creation models.

Kotlin Interface Syntax and Features

Despite their lack of constructors, Kotlin interfaces can contain properties without backing fields, abstract methods, and even method implementations using default methods. This enriches Kotlin interfaces, allowing developers to write more expressive and practical code.

Example of a Kotlin Interface:

kotlin
1interface Clickable {
2    // Abstract method
3    fun click()
4
5    // Method with default implementation
6    fun showOff() {
7        println("I'm clickable!")
8    }
9}
10
11class Button : Clickable {
12    override fun click() {
13        println("Button clicked")
14    }
15}

Implementing Interface Features: Practical Approach

When you need to instantiate objects complying with interface contracts but want the equivalent of a constructor's setup, here are some tactics:

1. Companion Object Factories:

Use a companion object to offer factory methods that can simulate constructor behavior by setting up properties or dependencies.

kotlin
1interface Loggable {
2    fun log(message: String)
3}
4
5class Logger private constructor(private val logLevel: Int) : Loggable {
6    companion object {
7        fun create(level: Int): Logger {
8            return Logger(level)
9        }
10    }
11
12    override fun log(message: String) {
13        println("Log level: $logLevel - $message")
14    }
15}
16
17val logger = Logger.create(1)
18logger.log("Starting the application.")

2. Abstract Classes as Alternatives:

When shared state or constructor behaviors are essential, consider using abstract classes that can provide constructors along with abstract method declarations.

kotlin
1abstract class Operable(val operation: String) {
2    abstract fun operate()
3
4    fun showOperation() {
5        println("Performing: $operation")
6    }
7}
8
9class Device : Operable("Computing") {
10    override fun operate() {
11        println("Device is operating")
12    }
13}
14
15val device = Device()
16device.operate()
17device.showOperation()

Advantages and Disadvantages of Interface without Constructors

Here is a table summarizing the pros and cons:

AdvantagesDisadvantages
Enforces strict protocol without state, ensuring pure polymorphism.Lack of state management often requires additional patterns.
Promotes decoupling and clean separation of capabilities.Interface-only solutions may necessitate more verbose setup.
Simplifies implementation by focusing solely on behavior.Requires workarounds for scenarios where state initialization is needed.

Conclusion

Kotlin interfaces represent a powerful tool that underlines Kotlin's commitment to efficient and elegant programming patterns. Despite lacking constructors, interfaces enrich the Kotlin programming landscape with flexibility and architectural cleanliness. Understanding how to effectively utilize interfaces alongside other constructs like companion objects and abstract classes can significantly enhance your software design capabilities. Kotlin’s distinct separation of interfaces from constructors is a deliberate choice, fostering clearer code and adherence to interface-based design.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.