Syntax to pass a function as parameter


#1

How do I pass a function as parameter?

class PropTest {
    val prop by Delegates.observable("initial", ::observe)

    fun observe(meta: PropertyMetadata, old: String, new: String) {

    }
}

The code above doesn't compile when function observe is within class PropTest. It seems to be ok, when I move the function outside of the class. Why is this the case?


#2

This is because when a function is declared within a class, it's a member function and has an impllicit "this" parameter, thus it doesn't correspond to the expected parameter type of Delegates.observable, which takes 3 parameters.

What could work is capturing current “this” in the context where it exists, passing a reference to the function closed on its receiver parameter. This would have other syntax and isn’t implemented yet (but is planned, see KT-1183)


#3

I guess the typechecker tell you that there is a type mismatch: a member of a class when used as a value is trated as an extension function, for it has one extra parameter: the receiving instance of the class


#4

Thank you for the explanation. Is this something that will generally not be possible or was it just not implemented yet?


#5

It will be possile.


#6

Yes please have such a workaround, perhaps C# like sytax.

void Fun1(String s) 
{
}
void Fun2(Action<String> action)
{
    action("Hello");
}
void Fun3()
{
    Fun2(Fun1);
}