Is there a lambda function in Scala?

I have a Java class that has access to a transaction context that I would like to use from Scala. So I thought that I would write a Java method that takes a Scala function and calls it inside a transaction -

class Context { @Transactional public void runInTx(Function0<scala.Unit> f) { f.apply(); } 

So far so good. I would like to be able to pass the Scala circuit to it

 def deleteItems(ids: Set[Long]) = { context.runInTx { ids foreach { dao.delete(_) } } } 

but it cannot, because runInTx does not actually call by name, and ids foreach { dao.delete(_) } is actually not Function0 .

Now I can solve this problem with a little thunk

 def deleteItems(ids: Set[Long]) = { def localApply(f: => Unit) = context.applyInTx(f _) localApply { ids foreach { dao.delete(_) } } } 

but it seems to me that I need a lambda function to create an unnamed Function0 from a code block.

Is there such a thing in the API or how can I write it?

+7
source share
1 answer

You can say that the compiler interprets the block as a function, not a statement that is called immediately by adding parameters (missing in this case).

So in this case:

 def deleteItems(ids: Set[Long]) = { context.runInTx {() => ids foreach { dao.delete(_) } } } 

() => ids foreach { dao.delete(_) } - the full form of the function literal. The compiler allows you to exclude the list of parameters in those places where it can conclude that the function is necessary - this is true for calling by name, but does not seem true when passed to a method that accepts Function

+11
source

All Articles