How might a Java program wrap a value into a scala.Either? For example, how would the following Scala code be written in Java?
Right("asdf")
Left(new Exception())
The following fails with "cannot find symbol method apply(java.lang.String)"
Right.apply("asdf");
The following fails with "cannot find symbol method apply(java.lang.Exception)"
Left.apply(new Exception());
If I understand the question correctly, assume you have the following Scala method:
def foo(stringOrDate: Either[String, Date]) {
//...
}
you can call it from Java code by single creating Either subclasses instances:
scalaObject.foo(new Left<String, Date>("abc"));
scalaObject.foo(new Right<String, Date>(new Date()));
If you want to pass functions from Java code, you have to implement Function* trait depending on the function arity:
def foo(stringOrStringFun: Either[String, () => String]) {
//...
}
In Java:
scalaObject.foo(new Left<String, scala.Function0<String>>("abc"));
scalaObject.foo(new Right<String, scala.Function0<String>>(
new scala.Function0<String>() {
@Override
public String apply() {
throw new RuntimeException();
}
}));
Of course in Scala it is much simpler as it supports lambdas on the syntax level:
foo(Left("abc"))
foo(Right(throw new RuntimeException()))
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