VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/implement-interface-in-kotlin/

⇱ Implement Interface in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement Interface in Kotlin

Last Updated : 13 Jan, 2022

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.

Basic Interface

A Kotlin interface contains declarations of abstract methods, and default method implementations although they cannot store state.

interface MyInterface {
 fun bar()
}

This interface can now be implemented by a class as follows:

class Child : MyInterface {
 override fun bar() {
 print("bar() was called")
 }
}

Interface with Default Implementations 

An interface in Kotlin can have default implementations for functions:

interface MyInterface {
 fun withImplementation() {
 print("withImplementation() was called")
 }
}

Classes implementing such interfaces will be able to use those functions without reimplementing

class MyClass: MyInterface {
 // No need to reimplement here
}
 val instance = MyClass()
 instance.withImplementation()

Properties

Default implementations also work for property getters and setters:

interface MyInterface2 {
 val helloWorld
 get() = "Hello World!"
}

Interface accessors implementations can't use backing fields

interface MyInterface3 {
 // this property won't compile!
 var helloWorld: Int
 get() = field
 set(value) { field = value }
}

Multiple Implementations

When multiple interfaces implement the same function, or all of them define with one or more implementing, the derived class needs to manually resolve proper call

Properties in Interfaces

You can declare properties in interfaces. Since an interface cannot have stated you can only declare a property as abstract or by providing default implementation for the accessors.

Conflicts when Implementing Multiple Interfaces with Default Implementations

When implementing more than one interface that has methods of the same name that include default implementations, it is ambiguous to the compiler which implementation should be used. In the case of a conflict, the developer must override the conflicting method and provide a custom implementation. That implementation may choose to delegate to the default implementations or not.

super keyword

interface MyInterface {
 fun funcOne() {
 // optional body
 print("Function with default implementation")
 }
}

Note:

If the method in the interface has its own default implementation, we can use the super keyword to access it.

super.funcOne()

Comment
Article Tags:
Article Tags:

Explore