I've been playing with Scala/Java interop lately, specifically, calling Scala (2.10.4) code from Java (7). It's been more pleasant than I expected, but a few things puzzle me.
E.g., in scala.runtime
I have a nice collection of AbstractFunction
abstract classes. But I don't see anything for methods with no return value. E.g., suppose I have the following Scala code:
class MyClass(name: String) {
def SayWhat(say_fn: String => Unit) = say_fn(name)
}
My understanding is that Java's void
is more or less Scala's Unit
, so I can pass something vaguely lambda-like with the following Java anonymous class:
import scala.Function1;
import scala.runtime.AbstractFunction1;
import scala.runtime.BoxedUnit;
public class MyProgram {
public static void main(String[] args) {
MyClass mc = new MyClass("Dan");
Function1<String, BoxedUnit> f = new AbstractFunction1<String, BoxedUnit>() {
public BoxedUnit apply(String s) {
System.out.println("Why, hello there " + s);
return null;
}
};
mc.SayWhat(f);
}
}
This obviously not the prettiest thing, but I appreciate the AbstractFunction
stuff, really, compared to what I would have to do otherwise! But is there really no AbstractProcedure
or something? Also, why does my "lambda" have to return BoxedUnit
?
A Scala trait with no method implementation is just an interface at the bytecode level and can thus be used in Java code like any other interface.
Everything is an Object. Scala is a pure object-oriented language in the sense that everything is an object, including numbers or functions. It differs from Java in that respect, since Java distinguishes primitive types (such as boolean and int ) from reference types.
Your function actually has to return BoxedUnit.UNIT
, which is the unit in question.
Unit
is an AnyVal
, not an AnyRef
, so it doesn't include null.
It is so much nicer when functions return interesting values.
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