scala-java8-compat icon indicating copy to clipboard operation
scala-java8-compat copied to clipboard

Wrong function conversion documentation

Open choedl opened this issue 7 years ago • 2 comments

I think the documentation regarding function conversion is wrong (at least the java code example) and doesn't compile.

To convert a java function to a scala function (like in baz) I have to write the following:

import static scala.compat.java8.JFunction.*;
...
// instead of return bar(functionConverters.asScalaFromFunction(f)) -> where should functionConverters come from?
return bar(func(f)); 
...

choedl avatar Aug 30 '17 10:08 choedl

Worked for me this way:

import java.util.function.*;

import scala.compat.java8.FunctionConverters.package$;

import static scala.compat.java8.FunctionConverters.package$.MODULE$;

class Example {
  private static package$ functionConverters = MODULE$;

  String foo(UnaryOperator<String> f) {
    return f.apply("halibut");
  }
  String bar(scala.Function1<String, String> f) {
    return foo(functionConverters.asJavaUnaryOperator(f));
  }
  String baz(Function<String, String> f) {
    return bar(functionConverters.asScalaFromFunction(f));
  }
}

Rorick avatar Apr 17 '19 18:04 Rorick

Some more options:

  1. JFunction1
import scala.compat.java8.JFunction1;
...
String baz(Function<String, String> f) {
    return bar((JFunction1<String, String>) f);
}
...
  1. FromJavaFunction
import scala.compat.java8.functionConverterImpls.FromJavaFunction;
...
String baz(Function<String, String> f) {
    return bar(new FromJavaFunction<>(f));
}
...

rdesgroppes avatar Apr 04 '20 11:04 rdesgroppes