Passing anonymous blocks to functions


#1
Hello!

First of all… I’ve been using Kotlin for sometime now, and I find it to be like Java++. Thank you for creating it!

Now…

I really like that you can easily pass these anonymous blocks to functions, like this:

``

class Foo {

  fun doSomethingWith(whatever: Whatever, callback: () -> Unit) {
          // do stuff
          // …
          // callback()
  }
}

Foo().doSomethingWith(whatever, {   println("done!")

})

I find that I use this quite often… but the only thing that bothers me, is the syntax of the block definition: “callback: () -> Unit”.

I find this a bit hard to remember and too verbose, because of the type declaration.

Is there no way to simply leave the “-> Unit” out? Or perhaps there already is a simpler way to achieve what I want?

Thanks.


#2

For now this is the only way. Not so many sane syntactic options available, so before we have type aliases, I'm doubt that this will be shortened


#3

fluxi wrote:

Foo().doSomethingWith(whatever, {
     println("done!")
})

In case you don't know, you can write that like this, when last arg is a function.

Foo().doSomethingWith(whatever) {
  println(“done!”)
}

See: http://kotlinlang.org/docs/reference/lambdas.html

Rob