Kotlin Interfaces

Kotlin interfaces are similar to Java 8. The interface keyword is used to define interfaces, allowing methods to have default implementations:

interface MyInterface { fun bar() //Not implemented fun foo() { //Implemented //Optional method body println("foo") } }

Implementing Interfaces

A class or object can implement one or more interfaces.

class Child : MyInterface { override fun bar() { //Method body } }

Example

interface MyInterface { fun bar() fun foo() { //Optional method body println("foo") } } class Child : MyInterface { override fun bar() { //Method body println("bar") } } fun main(args: Array<String>) { val c = Child() c.foo(); c.bar(); }

The output result is:

foo
bar

Properties in Interfaces

Properties in interfaces can only be abstract; initialization values are not allowed. Interfaces do not store property values. When implementing an interface, the properties must be overridden:

interface MyInterface{ var name:String //name property, abstract } class MyImpl:MyInterface{ override var name: String = "example" //Override property }

Example

interface MyInterface { var name:String //name property, abstract fun bar() fun foo() { //Optional method body println("foo") } } class Child : MyInterface { override var name: String = "example" //Override property override fun bar() { //Method body println("bar") } } fun main(args: Array<String>) { val c = Child() c.foo(); c.bar(); println(c.name) }

The output result is:

foo
bar
example

Function Overriding

When implementing multiple interfaces, you may encounter the problem of inheriting multiple implementations of the same method. For example:

Example

interface A { fun foo() { print("A") } //Implemented fun bar() //Not implemented, no method body, abstract } interface B { fun foo() { print("B") } //Implemented fun bar() { print("bar") } //Implemented } class C : A { override fun bar() { print("bar") } //Override } class D : A, B { override fun foo() { super<A>.foo() super<B>.foo() } override fun bar() { super<B>.bar() } } fun main(args: Array<String>) { val d = D() d.foo(); d.bar(); }

The output result is:

ABbar

In the example, interfaces A and B both define methods foo() and bar(). Both implement foo(), and B implements bar(). Because C is a concrete class that implements A, it must override bar() and implement this abstract method.

However, if we derive D from A and B, we need to implement all methods inherited from multiple interfaces and specify how D should implement them. This rule applies both to methods that inherit a single implementation (bar()) and to methods that inherit multiple implementations (foo()).

Other Extensions