Forgive me if this is a basic question in FP. Let's consider Optional monad. I know I can use map
to transform an Optional
to another Optional
based on a function (which will be called if optional has a value). But what if I have a function with two inputs, not one?
For example:
var data = Optional.of(100);
var result = data.map(x -> x * 2); //all good!
But what about:
int getData(Connection conn, int data) { ... }
var data = Optional.of(100);
var connection = getOptionalDataConnection();
var result = data.map(i -> getData(connection?, i)); //this does not work as the getData function only accepts non-optionals
I'm sure there is a term for this in FP world I'm just not familiar with it. But the idea is I have a map function which accepts "two" inputs, rather than one. And I want a helper/utility/... that will call my function if both inputs are there. But if any of them is "empty" should return Optional.empty()
.
What is this called and does Java support this?
What is this called and does Java support this?
This is called a monad, and yes, Java supports it via the flatMap function (monadic bind). Here demonstrated with just two optional integers:
var xo = Optional.of(100);
var yo = Optional.of(2);
var result = xo.flatMap(x -> yo.map(y -> x * y));
In this example, result
is an Optional
value holding the integer 200
.
For the particular example in the OP, you actually don't need a monad, since using the capabilities of the Maybe/Optional applicative functor would be sufficient. I'm not well-versed in the Java ecosystem, however, and I don't see any apply-like methods in the API documentation. You could probably write it yourself, but my experience from Java's cousin language C# tells me that applicative functors are awkward in such languages.