Created
December 3, 2011 17:55
-
-
Save julienrf/1427697 to your computer and use it in GitHub Desktop.
Using scala.Function1 from Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lambda | |
object JFunction { | |
def fun[T1, R](g: JFunction1[T1, R]): T1 => R = new (T1 => R) { | |
override def apply(t: T1) = g.apply(t) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lambda; | |
public interface JFunction1<T1, R> { | |
R apply(T1 t); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lambda; | |
import scala.Option; | |
import scala.Some; | |
public class Lambda { | |
public static void main(String[] args) { | |
Option<Integer> opt = new Some<Integer>(42); | |
// Java 7 | |
System.out.println(opt.map(JFunction.fun(new JFunction1<Integer, String>() { | |
@Override | |
public String apply(Integer n) { | |
return n.toString(); | |
} | |
}))); | |
// Java 8 lambda syntax | |
System.out.println(opt.map(JFunction.<Integer, String>fun(n -> n.toString()))); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lambda; | |
import scala.Option; | |
import scala.Some; | |
import scala.runtime.AbstractFunction1; | |
public class Lambda { | |
public static void main(String[] args) { | |
Option<Integer> opt = new Some<Integer>(42); | |
// Java 7 | |
System.out.println(opt.map(new AbstractFunction1<Integer, String>() { | |
@Override | |
public String apply(Integer n) { | |
return n.toString(); | |
} | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment