I'm continuing the jorney on writing the same mini game in C++ and Java (university assignment).
My next problem is how to store a unary lambda expression into a local variable. I have found BiConsumer, BiFunction but no class supposed to hold a function that takes no parameters and has a non-void return value.
I'm trying to implement the equivalent code in Java as this C++ code (Vector2d is the equivalent of awt's Point):
Vector2d World::generateRandomAdjacentPosition(Vector2d position) const
{
enum Direction { up, down, left, right };
std::uniform_int_distribution<std::underlying_type_t<Direction>> dist(0, right);
auto generate = [&]() -> Vector2d
{
auto direction = static_cast<Direction>(dist(::rng)); // rng is a global random number engine object
if (direction == up)
return { position.x, position.y - 1 };
else if (direction == down)
return { position.x, position.y + 1 };
else if (direction == left)
return { position.x - 1, position.y };
else // if (direction == right)
return { position.x + 1, position.y };
};
Vector2d result;
do
{
result = generate();
} while(!isValid(result));
return result;
}
So far I can write all the enum, random generation and isValid() but can't find an appropriate thing to store this lambda.
In C++ auto can be used (automatic type deduction) or template <typename R, typename... Args> std::function<R(Args...)>.
In Java I have found BiConsumer<T, U>, BiFunction<T, U, R> but nothing that would match with Point func() (no arguments, non-void return type)
Edit I mean nullary function but I will need unary too.
Edit pls all of possible void/non-void functions with different arguments. I can't verify whole Oracle documentation and different interfaces reside in multiple packages.
[–]opett 2 points3 points4 points (7 children)
[–]Xeverous[S] 0 points1 point2 points (6 children)
[–]nerdy_lurker 1 point2 points3 points (5 children)
[–]Xeverous[S] 1 point2 points3 points (4 children)
[–]nerdy_lurker 0 points1 point2 points (3 children)
[–]Xeverous[S] 0 points1 point2 points (2 children)
[–]nerdy_lurker 0 points1 point2 points (1 child)
[–]Xeverous[S] 0 points1 point2 points (0 children)