Search code examples
kotlinfunctional-interface

How to implement functional interface for class by lambda?


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?


Solution

  • It can be implemented with delegate pattern.

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