Search code examples
kotlinfunctional-interface

Kotlin shorthand for implementing a functional interface with annotations


In Kotlin, is there a way to define an annotated class implementing a functional interface that is shorter than the following:

@Foo
class Bar : Runnable {
    override fun run() = ...
}

I'm hoping to find something like the following made-up syntax:

@Foo
fun Bar : Runnable () = ...

Due to interoperability reasons, I must end up with a class annotated with @Foo implementing Runnable or an instance of a class annotated with @Foo implementing Runnable.


Solution

  • I guess the shortest syntax would be this:

    @Foo object: Runnable {
        override fun run() {}
    }
    

    If you annotate lambdas, the annotation will be applied on the invoke function rather than the implemented class.