Sunday 19 April 2020

Kotlin : Interface (Post 12)

Hi ,

Here I am again sharing you one more concept in Kotlin programming language i.e. Interface.

In kotlin , the interfaces work slightly different . In jave we all know that we need to implement the Interface , then override the functions to execute that interface , but here in Kotlin , we can directly execute the interface and pass the argument within the function using "object" keyword , let's take a look :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        getSum(4,8, object : MyInterface{
            override fun execute(sum: Int) {
                println(sum)
            }
        })
    }
   fun getSum( a : Int , b : Int , listener : MyInterface ) {
      listener.execute(a+b)
   }
    interface  MyInterface {
        fun execute(sum : Int)
    }

Also one more thing , for interface in Kotlin , few methods can also contains the body also inside the interface , same as abstract class. What makes them different from abstract classes is that interfaces cannot store state :

  interface  MyInterface {
        fun execute(sum : Int)
        fun show (){
            println("Hi I am in interface")
        }
    }

In class level , interface will implement like this :

class Child : MyInterface {
    override fun execute(sum: Int) {
        // body
    }
}

So in this way we can implement the interfaces in Kotlin . In next post I will share one more interesting concept in Kotlin Language  , till then Happy Coding :) 

No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...