Kotlin Interfaces

Kotlin Interfaces

Hello there 👋, let's dive into interfaces today. I talked about abstract classes If you read my previous article in this series. These go hand in hand with interfaces and I will not talk much about them here.

So what are Interfaces?

image.png
In Object-Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X". ... The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.

It is actually a concept of abstraction and encapsulation. For a given "box", it declares the "inputs" and "outputs" of that box. In the world of software, that usually means the operations that can be invoked on the box (along with arguments) and in some cases the return types of these operations.

At a high level, an interface acts as a blueprint for designing classes. Like classes, interfaces define methods. Unlike classes, these methods are abstract. An abstract method is one that the interface simply defines. It doesn’t implement the methods. image.png This is done by classes, which then implement the interface and give concrete meaning to the interface’s abstract methods.

Kotlin interfaces are similar to abstract classes. However, interfaces cannot store states whereas abstract classes can.

Meaning, interface may have property but it needs to be abstract or has to provide accessor implementations. Whereas, it's not mandatory for the property of an abstract class to be abstract.

Kotlin

Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations.

An interface is defined using the keyword interface:

interface MyInterface {
    fun bar()
    fun foo() {
      // optional body
    }
}

Python

Python’s approach to interface design is somewhat different when compared to languages like Kotlin, Java, Go, and C++. These languages all have an interface keyword, while Python does not.

Interfaces are not necessary for Python. This is because Python has proper multiple inheritances, and also duck-typing, which means that the places where you must have interfaces in other languages, you don't have to have them in Python.

However, we can still implement the same trick we used in the previous blog to have interfaces using abc module

Resources

🎈 Stack-OverFlow
🎈 Kotlin Docs
🎈 Baeldung

Please consider subscribing, sharing or liking this if you have enjoyed my simple article

Ronnie Atuhaire 🤓