zeromem
zeromem

Reputation: 381

Java Call Scala HashMap's getOrElse

My java code looks like (java8, lambda supported):

import scala.collection.mutable.HashMap;
...
public void test() {
  HashMap<Integer, String> map = new HashMap<>();
  map.put(1, "Hello");

  // ERROR: parameter need Function0<B1>. given int, ()->"World".
  map.getOrElse(1, () -> "World");
}

when I build the project, it tells me parameter need Function0<B1>. given int, ()->"World". BUT my IDE(Idea) do not remind me this is an error, even it prompts me reduce code "new Function0(){...}" to "() -> World". So How can I call scala (HashMap)'s getOrElse method in java code (java8)?

Upvotes: 2

Views: 806

Answers (1)

Jack
Jack

Reputation: 133609

I think that the problem is that a Java8 functional interface is not directly convertible to scala functions.

This will be addressed in Scala 2.12 (as stated here). The solution seems to be to use a wrapper which makes the conversion for you.

More details here, the example given in the readme is what you are looking for:

import scala.concurrent.*;
import static scala.compat.java8.JFunction.*;

class Test {
    private static Future<Integer> futureExample(Future<String> future, ExecutionContext ec) {
        return future.map(func(s -> s.toUpperCase()), ec).map(func(s -> s.length()), ec);
    }
}

Upvotes: 3

Related Questions