Smooth way of using Function<A, R> java interface from scala?

随声附和 提交于 2019-12-01 17:51:09

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.

To expand on paradigmatic answer. Here is how you go about figuring out the implicit. Implicit conversions come into play when the types don't check. When that happens, the compiler will search for an implicit conversion to use so that types match.

After cleaning up your example a bit, in the REPL, the compiler would show:

scala> ac.myMethod((s:String) => s + "!")
<console>:9: error: type mismatch;
 found   : String => java.lang.String
 required: Func[java.lang.String,?]
              ac.myMethod((s:String) => s + "!")

So the compiler tells you it found a (String) => (String) but needs a Func[String, ?]. Therefore you want to provide an implicit conversion between the found type and the required type. So the signature should be something like:

implicit def fun2Func(fun: (String) => String): Func[String,String]

Then, the next step is to realize that the implicit conversion can be generalized with types A and R.

On a sidenote, I wonder if you'd be better of by re-using something of the shelf like http://code.google.com/p/guava-libraries/.

I don't know exactly but maybe functional Java http://functionaljava.org/ could help you and your collegues. What functions exactly you try to gather in your 'pseudo-fp' lib?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!