顺利使用Function< A,R>从Scala的Java接口? [英] Smooth way of using Function<A, R> java interface from scala?
问题描述
在工作中,大多数人使用Java,而我正在与Scala合作。我们决定在一个将用Java编写的库中收集一些通用的类。现在我想添加一些伪函数编程到库中,看看下面的内容:
Here at work most people use Java, while I am working with Scala. We have decided to gather some common classes in an library which will be written in Java. Now I want to add some pseudo-functional programming to the library, take a look at the following:
java:
public interface Func<A, R> {
public R f(a A);
}
public AClass {
public <R> ArrayList<R> myMethod(
Func<String, R> func
) {
// ...
}
}
在java中的用法:
AClass ac = new AClass();
ArrayList<String> al = ac.myMethod(
new Func<String, String> (
public String f(String s) {
return s + "!";
}
})
以上并不完全是退出(从scala的角度来看更像是令人生畏的)。有什么办法可以召唤一些scala魔法,以便能够在scala中做如下的事情:
The above is not exactly exiting (more like daunting actually, from a scala perspective). Is there any way to summon some scala magic to be able to do something like the following in scala:
var ac = new ACLass
var al = ac.myMethod(str => str + "!") // alternative 1
al = ac.myMethod { case: str:String => str + "!" } // alternative 2
我混淆了一段时间的implicits,但无法将事情整理出来= P。
I messed around with implicits for a while but couldn't get things sorted out =P.
推荐答案
隐式转换:
With implicit conversions:
object FuncConversions {
implicit def func2function[A,R]( fn: (A) => R ) =
new Func[A,R] {
def f(a: A) = fn(a)
}
}
不要忘记在您的作用域中导入转换:
Don't forget to import the conversion in your scope:
import FuncConversions._
您也可以实现相反的转换。
You can also implement the opposite conversion.
这篇关于顺利使用Function< A,R>从Scala的Java接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!