Reputation: 1480
In Java 8 I want to create something that returns an argument or creates an instance if the argument is null.
I could do this by creating a static method or a UnaryOperator. Are the following approaches technically the same or are there technical differences that I should be aware of with either approach:
Static Method
static Cat initOrReturn(Cat c) {
if (c==null) {
return new Cat();
}
return c;
}
Function
UnaryOperator<Cat> initOrReturn = c -> {
if (c==null) {
return new Cat();
}
return c;
}
Upvotes: 3
Views: 1941
Reputation: 123
You can think about function as a "value" - something that can be stored to variable, and passed around.
This "value" can be used as e.g. method parameter to (during runtime) dynamically change part of method implementation.
Take a look at this basic example. Hope that can illustrate idea:
static Number functionsUsageExample(Integer someValue, UnaryOperator<Number> unaryOperator) {
if (someValue == 1) {
//do something
}
Number result = unaryOperator.apply(someValue); // dynamically apply supplied implementation
// do something else
return result;
}
public static void main(String[] args) {
UnaryOperator<Number> add = i -> i.doubleValue() + 20;
UnaryOperator<Number> multiply = i -> i.intValue() * 3;
var additionResult = functionsUsageExample(1, add);
var multiplicationResult = functionsUsageExample(1, multiply);
//additionResult value is: 21.0
//multiplicationResult value is: 3
}
Function can be also used as a 'helper methods' stored inside method block. This way you will not corrupt class scope with method that is used only in one place.
Upvotes: 0
Reputation: 6579
First your code has syntax error, in the second block first line between c
and {
there should be a ->
.
The second one creates an anonynous object, the first one only creates a static method.
So they're not the same.
Also, static methods can be used in stream API.
If you have:
class A {
static Object a(Object x) { return x; /* replace with your code */ }
}
You can:
xxxList().stream().map(A::a)
Creating a method is often considered dirty, because it's globally visible.
It's recommended to use lambda expressions without declaring a variable.
Upvotes: 3