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.
Frage
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
?
Lösung
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.