A smooth way to use the scala? <A, R> java functional interface?

Here at work, most people use Java while I work with Scala. We decided to collect some common classes in a library to be written in Java. Now I want to add pseudo-functional programming to the library by looking 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
    ) {
        // ...
    }
}

usage in java:

AClass ac = new AClass();
ArrayList<String> al = ac.myMethod(
                            new Func<String, String> (
                                public String f(String s) {
                                    return s + "!";
                                }
                            })

The above does not quite work out (more like scary, from the point of view of scala). Is there a way to invoke 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

For a while I was busy with implications, but I couldn’t make out things = P.

+5
source share
3 answers

:

object FuncConversions {
  implicit def func2function[A,R]( fn: (A) => R ) =
    new Func[A,R] {
      def f(a: A) = fn(a)
    }
}

:

import FuncConversions._

.

+14

. . , . , , .

REPL :

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 + "!")

, , (String) => (String), Func[String, ?]. . , :

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

, A R.

, , - , http://code.google.com/p/guava-libraries/.

+6

I don’t know for sure, but maybe functional Java http://functionaljava.org/ can help you and your colleagues. What functions are you trying to build in your pseudo-fp lib?

+3
source

All Articles