user9900987
user9900987

Reputation:

Passing a method vs. passing an interface in Kotlin

When I use Java, it's easy to use interface to send method to another class. And it's good in OOP way:

class A{
   private FooListener listener;

   public A(FooListener listener){
        this.listener = listener;
   }

   public void foo(){
        // do something
        listener.method();
   }
}

But in Kotlin, we can easily pass the method using parameter like this:

class A(val method: () -> Unit ) {
    fun foo(){ 
        // do something
        method()
    }
}

is that code is still good in OOP way? or i should use interface? i think its ok to pass the method directly.

Upvotes: 2

Views: 207

Answers (2)

mightyWOZ
mightyWOZ

Reputation: 8315

In Kotlin both of these methods are correct and can be used depending on your use case. Unlike Java which was primarily an Object Oriented language but later included some functional programming features with the introduction of java 8, Kotlin from beginning is designed to support both Object Oriented as well as functional approach.

as Kotlin in Action states

Kotlin lets you program in the functional style but doesn’t enforce it.

When you need it, you can work with mutable data and write functions that have side effects without jumping through any extra hoops. And, of course, working with frameworks that are based on interfaces and class hierarchies is just as easy as with Java.

When writing code in Kotlin, you can combine both the object-oriented and functional approaches and use the tools that are most appropriate for the problem you’re solving.

Upvotes: 1

Timotej Leginus
Timotej Leginus

Reputation: 294

The code is OK. It's better to write more readable code than a "this must be OOP" code.

Upvotes: 0

Related Questions