Kotlin Interface Example

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

Kotlin - Simple Interface Example

package net.javaguides.kotlin.examples

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

class Child: MyInterface {
    override fun bar() {
        println("inside bar method");
    }

    override fun foo() {
        println("inside foo method");
    }
}

fun main(args: Array < String > ) {
    var myInterface = Child();
    myInterface.bar();
    myInterface.foo();
}
Output:
inside bar method
inside foo method
Create interface:
interface MyInterface {
    fun bar()
    fun foo() {
        // optional body
    }
}
Implementation of above interface:
class Child: MyInterface {
    override fun bar() {
        println("inside bar method");
    }

    override fun foo() {
        println("inside foo method");
    }
}

Comments