How to pass a function as parameter to another?


#1

given funciton foo :

fun foo(m: String, bar: (m: String) -> Unit) {   bar(m) }

we can do:

``

  foo(“a meesage”, { println(“this is a message: $it”) } )
  //or
  foo(“a meesage”)  { println(“this is a message: $it”) }
  

now lets say, we have following function:

fun buz(m: String) {   println("another message: $m") }

is there a way, i can pass "buz" as a parameter to "foo" ? something like:
foo("a message", buz)

#2

I believe the only current way to do this is to change your definition of buz and set it as a property:

val buz: (String)->Unit = { m->   println("another message: $m") }

However, there has been some discussions about this here, and I think supporting passing named functions like that makes sense. I'd also like to be able to do this:

class Zoo {   fun buz(m: String) { } }

val z = Zoo()
foo(“a message”, z.buz)


This would allow the callback to have the context of an object. You can currently do this by wrapping it:

val z = Zoo() foo("a message", {m-> z.buz(m)})


#3

There's an old issue filed about this:  http://youtrack.jetbrains.com/issue/KT-1183?projectKey=KT

Vote!


#4

We are currently working on it. The syntax will be the following:

``

foo(“a message”, myPackage::buz) // myPackage is a name of the package
foo(“a message”, ::buz) // buz will be looked up in current scope, works if “buz” is declared in current package or imported


#5

great. how about this case ?

myobject::buz  // buz belong to a class and myobject is an instance of such class.

would that be supported too ?


#6

In the nearest future, we'll support only syntax with class or package before "::" symbols. Mentioned use case will be covered by standard library function taking object and member function, returning function with "captured" receiver object, used like this:

bind(myobject, buz)

Later, we are planning to support syntax you offer (with expression before “::”), but exact syntax may appear a bit different.


#7

Fantastic, this would open the door for some limited but potentially very useful dependent typing.


#8

Evgeny:

This syntax will let us just pass the member function as a parameter to other function or will return it as a function?. I mean, this will be possible?:

val f:(Foo) -> Bar = myPakage::buz

Thanks


#9

This will be a syntactic sugar for trivial function literal which passes all its parameters to referred function. Answering your questions, yes it will return function expression, and your sample will work.


#10

Cool, if you combine it with Function composition provided by funKTionale you could do nice things like this:

val f:(Foo) -> Bar = myPackage::buz forwardCompose anotherPackage::otherBuz


#11

Yes.