2016-10-12 25 views
2

我的Java代碼如下所示(java8,拉姆達支持):Java調用斯卡拉的HashMap的getOrElse

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"); 
} 

當我生成項目,它告訴我parameter need Function0<B1>. given int,()->"World". 但我的IDE(想法)不要再提醒我這是一個錯誤,甚至會提示我將代碼「new Function0(){...}」減少爲「() - > World」。 那麼如何在Java代碼(java8)中調用scala(HashMap)的getOrElse方法?

回答

3

我認爲問題是Java8功能接口不能直接轉換爲scala函數。

這將在斯卡拉2.12(如陳述here)解決。解決方案似乎是使用一個包裝器,它可以爲您進行轉換。

更多細節here,自述給出的例子是,你在找什麼:

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); 
    } 
}