Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala's Either, Right and Left from Java

Tags:

java

scala

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());
like image 925
Mike Slinn Avatar asked Mar 16 '26 05:03

Mike Slinn


1 Answers

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()))
like image 61
Tomasz Nurkiewicz Avatar answered Mar 17 '26 20:03

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!