Kotlin tutorial for Beginners – Kotlin Interfaces

Hits: 1

Kotlin Interfaces

In this article, you will learn about interfaces and how to implement it in Kotlin with the help of examples.

Meaning, interface may have property but it needs to be abstract or has to provide accessor implementations.


Abstract classes in Kotlin are similar to interface with one important difference. It’s not mandatory for properties of an abstract class to be abstract or provide accessor implementations.


How to define an interface?

Keyword interface is used to define interfaces in Kotlin. For example,

interface MyInterface {

    var test: String   // abstract property

    fun foo()          // abstract method
    fun hello() = "Hello there" // method with default implementation
}

Here,

  • an interface MyInterface is created.
  • the interface has an abstract property test and an abstract method foo().
  • the interface also has a non-abstract method hello().

 


How to implement interface?

Here’s how a class or object can implement the interface:

interface MyInterface {

    val test: Int   // abstract property

    fun foo() : String   // abstract method (returns String)
    fun hello() {   // method with default implementation
        // body (optional)
    }
}

class InterfaceImp : MyInterface {

    override val test: Int = 25
    override fun foo() = "Lol"

    // other code
}

Here, a class InterfaceImp implements the MyInterface interface.

The class overrides abstract members (test property and foo() method) of the interface.


Example: How interface works?

interface MyInterface{

    val test: Int

    fun foo() : String

    fun hello() {
        println("Hello there, pal!")
    }
}

class InterfaceImp : MyInterface {

    override val test: Int = 25
    override fun foo() = "Lol"

}

fun main(args: Array<String>) {
    val obj = InterfaceImp()

    println("test = ${obj.test}")
    print("Calling hello(): ")

    obj.hello()

    print("Calling and printing foo(): ")
    println(obj.foo())
}

When you run the program, the output will be:

test = 25
Calling hello(): Hello there, pal!
Calling and printing foo(): Lol

As mentioned above, an interface may also have a property that provide accessor implementation. For example,

interface MyInterface{

    // property with implementation
    val prop: Int
        get() = 23
}

class InterfaceImp : MyInterface {
    // class body
}

fun main(args: Array<String>) {
    val obj = InterfaceImp()

    println(obj.prop)
}

When you run the program, the output will be:

23

Here, prop is not abstract. However, it’s valid inside the interface because it provides implementation for accessor.

However, you cannot do something like val prop: Int = 23 inside the interface.


Implementing Two or More Interfaces in a Class

Kotlin does not allow true multiple inheritance. However, it’s possible to implement two or more interfaces in a single class. For example,

interface A{

    fun callMe() {
        println("From interface A")
    }
}

interface B{
    fun callMeToo() {
        println("From interface B")
    }
}

// implements two interfaces A and B
class Child: A, B

fun main(args: Array<String>) {
    val obj = Child()

    obj.callMe()
    obj.callMeToo()
}

When you run the program, the output will be:

From interface A
From interface B

Resolving overriding conflicts (Multiple Interface)

Suppose, two interfaces(A and B) have a non-abstract method with the same name (let’s say callMe() method). You implemented these two interfaces in a class (let’s say C). Now, if you call the callMe() method using the object of class C, compiler will throw error. For example,

interface A{

    fun callMe() {
        println("From interface A")
    }
}

interface B{
    fun callMe() {
        println("From interface B")
    }
}

class Child: A, B 

fun main(args: Array<String>) {
    val obj = Child()

    obj.callMe()
}

Here’s the error:

Error:(14, 1) Kotlin: Class 'C' must override public open fun callMe(): Unit defined in A because it inherits multiple interface methods of it

To solve this issue, you need to provide your own implementation. Here’s how:

interface A{

    fun callMe() {
        println("From interface A")
    }
}

interface B{
    fun callMe() {
        println("From interface B")
    }
}

class C: A, B {
    override fun callMe() {
        super<A>.callMe()
        super<B>.callMe()
    }
}

fun main(args: Array<String>) {
    val obj = C()

    obj.callMe()
}

Now when you run the program, the output will be:

From interface A
From interface B

Here, explicit implementation of callMe() method is provided in class C.

class C: A, B {
    override fun callMe() {
        super<A>.callMe()
        super<B>.callMe()
    }
}

The statement super<A>.callMe() calls the callMe() method of class A. Similarly, super<B>.callMe() calls the callMe() method of class B.

 

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.