从 Java #map 调用 Scala Monad [英] Calling Scala Monads from Java #map
问题描述
我有一个 scala.collection.immutable.List
的实例,我想在它上面调用 map
方法,但是来自 Java.
I have an instance of a scala.collection.immutable.List
and I want to call the map
method on it, BUT from Java.
我需要提供一个 CanBuildFrom
.
我注意到许多 Scala 集合伴随对象包含隐式 <code>CanBuildFrom 实例,但我无法确定我需要使用哪一个.
I noticed that a lot of the scala collections companion objects contain implicit CanBuildFrom
instances, but I cannot work out which one I need to use.
这是我的 Java 代码:
Here is my Java code:
Function1<WeatherData, BigDecimal> mapper = new AbstractFunction1<WeatherData, BigDecimal>(){
@Override
public BigDecimal apply(WeatherData data) {
return data.getTemps().reduce(adder).divide(new BigDecimal(data.getTemps().size()));
}
};
scala.collection.immutable.List<WeatherData> data = ...
data.map(mapper, ???);
我应该传递什么作为 CanBuildFrom(第二个参数?)
What should I pass as a CanBuildFrom (the second parameter?)
PS 使用 Scala 2.10-M5
PS Using Scala 2.10-M5
推荐答案
您实际上可以在 Java 中正确获取类型而无需大惊小怪:
You can actually get the types right in Java without too much fuss:
import scala.collection.Traversable;
import scala.collection.generic.CanBuildFrom;
import scala.collection.immutable.List;
import scala.collection.mutable.Builder;
import scala.runtime.AbstractFunction1;
public class ScalaMapTest {
public static List<Integer> parseInts(List<String> xs) {
final CanBuildFrom<List<?>, Integer, List<Integer>> builder =
List.<Integer>canBuildFrom();
return xs.map(
new AbstractFunction1<String, Integer>() {
public Integer apply(String s) {
return Integer.parseInt(s);
}
},
new CanBuildFrom<Traversable<String>, Integer, List<Integer>>() {
public Builder<Integer, List<Integer>> apply() {
return builder.apply();
}
public Builder<Integer, List<Integer>> apply(Traversable<String> from) {
return builder.apply(from.toList());
}
}
);
}
}
它仍然像罪一样丑陋,但它有效.问题在于 CanBuildFrom
上的通配符是您从 List
对象上的 canBuildFrom
方法获得的,但幸运的是您可以创建自己的 具有正确类型的 CanBuildFrom
包装器.
It's still ugly as sin, but it works. The problem is that wildcard on the CanBuildFrom
you get from the canBuildFrom
method on the List
object, but fortunately you can create your own CanBuildFrom
wrapper with the right type.
这篇关于从 Java #map 调用 Scala Monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!