Kotlin Interface With Examples

In this tutorial, we’ll be looking into interfaces in Kotlin. Kotlin interface is like contracts that can be used by classes for specific behaviors.

Kotlin Interface

Interfaces in Kotlin contain the definitions of functions and properties that are abstract.

Interfaces can have the implementation of the functions.

Also, interfaces can have non-abstract properties by defining their getters and setters.

But still, an interface can’t store the state. Interfaces are useless unless they’re implemented by a class.

An interface can’t have any constructor.

Defining an Interface

An interface in Kotlin can be defined using the keyword interface.

The printMe() function is non-abstract since it contains an implementation.

Additionally, we can also declare the property, provided we set accessor methods to it.

We cannot use the backing field from Properties in interfaces since an interface doesn’t store any state and hence no previous values.

Implementing Interfaces

The above interfaces that we’ve defined can be implemented over Kotlin Class as shown below.

We need to implement all the abstract properties of the interface or else set the class as an abstract class.

An override modifier overrides the property/function from the interface defined.

Implementation of non-abstract properties/functions is not necessary.

Let’s initialize the class in the main function.

kotlin-interface

Overriding properties inside the constructor

Properties can be overriden as constructor parameters of the class too.

Implementing Multiple Interfaces

A class can implement multiple interfaces too using the above concept.
Let’s look at an example wherein both the interfaces have the same functions defined as shown below.

In this case, if at all we override the function implementation in our class, our class would have a single common overridden implementation as shown below.

What if we need to access the function from the interface?

We use the keyword super.

Now in the above code, using super would give a compile time error since the compiler doesn’t know which of the interfaces to goto.

So in such cases in Kotlin, we need to specify the interface along with super as shown below.

Another example:

That’s all for kotlin interface tutorial.

Reference: Official Documentation

By admin

Leave a Reply