Which use-cases have classes that are extended from lambdas?

class A: ()-> Unit {
    override fun invoke() {

I don’t really know. I don’t think this was added as a feature. This is just a side product of how lambdas work in kotlin and java.
() -> Unit is just an alias for Function0<Unit> (I think, it might be KFunction0<Unit>. Those special hidden interfaces are a bit confusing, but it’s not important anyways).
All lambdas are classes. Otherwise there is no way of passing lambdas as arguments or capturing values.


In fact, there are a lot of uses. For example, parametric functions. Usually, when you are passing function as argument, you construct is a s lambda, but there are cases when you want some kind of parametric constructor which works in a specific way and does not capture values from environment. Sadly, the use of this feature is limited in MPP since JS does not allow to inherit anything from function. Of course, most of those things could be done using lambda capture instead of inheritance.

1 Like

I’ve had the same guesses about it, but can’t invent anything more.
Anyway opinion it’s very interesting feature that could be used more useful than just in this way.


Correct me if I’m wrong, but the quoted code isn’t actually a lambda, is it?

()-> Unit is a type: the type of a function taking no parameters and returning no useful result. In fact, as @Wasabi375 said, it’s an interface type.

So A is a class which implements that interface, and overrides its invoke() method.

There’s no reason to disallow this, but I can’t think of many reasons you’d want to use it over lambdas (where possible) or anonymous functions.

1 Like