I was wondering if there is any way to pull that in Java. I think it is not possible without native support for closures.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Yes, I agree with @Jérôme, curring in Java 8 is not supported in a standard way like in Scala or other functional programming languages.
Well, Scala, Clojure or Haskell (or any other functional programming language...) are definitely THE languages to use for currying and other functional tricks.
Having that said is certainly possible to curry with Java without the super amounts of boilerplate one might expect (well, having to be explicit about the types hurts a lot though - just take a look at the
curried
example ;-)).The tests bellow showcase both, currying a
Function3
intoFunction1 => Function1 => Function1
:as well as partial application, although it's not really typesafe in this example:
This is taken from a Proof Of Concept I've just implemented for fun before JavaOne tomorrow in an hour "because I was bored" ;-) The code is available here: https://github.com/ktoso/jcurry
The general idea could be expanded to FunctionN => FunctionM, relatively easily, though "real typesafety" remains a problem for the partia application example and the currying example would need a hell lot of boilerplaty code in jcurry, but it's doable.
All in all, it's doable, yet in Scala it's out of the box ;-)
One more take on the Java 8 possibilities:
You can also define utility methods like this one:
Which gives you an arguably more readable syntax:
Java 8 (released March 18th 2014) does support currying. The example Java code posted in the answer by missingfaktor can be rewritten as:
... which is quite nice. Personally, with Java 8 available I see little reason to use an alternative JVM language such as Scala or Clojure. They provide other language features, of course, but that's not enough to justify the transition cost and the weaker IDE/tooling/libraries support, IMO.
EDIT: As of 2014 and Java 8, functional programming in Java is now not only possible, but also not ugly (I dare to say beautiful). See for example Rogerio's answer.
Old answer:
Java isn't best choice, if you are going to use functional programming techniques. As missingfaktor wrote, you will have to write quite big amount of code to achieve what you want.
On the other hand, you are not restricted to Java on JVM - you can use Scala or Clojure which are functional languages (Scala is, in fact, both functional and OO).
An another choice is here for Java 6+
then you could achieve currying by this way