I have a Java class that has access to a transaction context that I'd like to use from Scala. So I thought that I'd write a Java method that takes a Scala function and calls it inside the transaction -
class Context {
@Transactional public void runInTx(Function0<scala.Unit> f) {
f.apply();
}
So far so good. I'd like to be able to pass a Scala closure to it
def deleteItems(ids: Set[Long]) = {
context.runInTx { ids foreach { dao.delete(_) } }
}
but can't because runInTx
isn't actually call by name, and ids foreach { dao.delete(_) }
isn't actually a Function0
.
Now I can solve this problem with a small 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 produce an unnamed Function0
out of a code block.
Does such a thing exist in the API, or how would I go about writing it?
AWS Lambda's Java support also makes it easy to write Lambda functions in other jvm-based languages. Let's take a look at how you can do that for Scala.
Lambda expressions, for simple functions that can be written as an expression. (Lambdas do not support multi-statement functions or statements that do not return a value.) Local def s inside the function calling into Spark, for longer code. Top-level functions in a module.
We can define multiple arguments in the anonymous function. We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function. var myfun 1 = () => { "Welcome to GeeksforGeeks...!!" }
A Scala method is a part of a class which has a name, a signature, optionally some annotations, and some bytecode where as a function in Scala is a complete object which can be assigned to a variable. In other words, a function, which is defined as a member of some object, is called a method.
You can tell the compiler to interpret the block as a function rather than a statement to be called immediately by adding the (in this case lack of) parameters.
So in this case:
def deleteItems(ids: Set[Long]) = {
context.runInTx {() => ids foreach { dao.delete(_) } }
}
() => ids foreach { dao.delete(_) }
is the full form of the function literal. The compiler allows the parameter list to be omitted in places where it can infer that a function is required - this is true for call by name, but doesn't seem to be true when passing to a method taking a Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With