Home > OS >  How to implement functional interface for class by lambda?
How to implement functional interface for class by lambda?

Time:08-08

I have Decorator interface:

fun interface Decorator {
    decorate(text: String): String
}

And I want to implement it for class Padded by lambda like this:

class Padded(padding: String) : Decorator {
    text -> "$padding $text $padding"
}

I don't want to write method signature, introduce another class wrapper, or replace class with higher-order function. How can I do it?

CodePudding user response:

The point of using functional interfaces is to be able to provide a lambda in places where an instance of such interface is required, instead of instantiating a class that implements that interface (or creating an anonymous object implementing it). Functional interfaces don't help with implementing interfaces in class declarations.

What you could do is declare a Padded function, which returns an instance of Decorator using a lambda:

fun Padded(padding: String) = Decorator { "$padding $it $padding" }

But if you want a class, you'll have to implement the function explicitly:

class Padded(padding: String) : Decorator {
    override fun decorate(text: String) = "$padding $text $padding"
}

which is honestly the same number of lines as the syntax you were looking for, and very clear to everyone.

CodePudding user response:

It can be implemented with delegate pattern.

class Padded(padding: String) : Decorator by (Decorator {
    text -> "$padding $text $padding"
})
  • Related