guys. I have an enum class with directions and degree values in them. With "ofDegrees" method, I have to return a Direction object with the name of field (for example: SW) if input degrees match with direction degrees, and if there’s no match to return empty Optional.
I tried with converting the degrees input to object and then check for equality between the input and enum values.
public enum Direction {
N(0), NE(45), E(90), SE(135), S(180), SW(225), W(270), NW(315);
Direction(final int degrees) {
this.degrees = degrees;
}
private int degrees;
public static Direction ofDegrees(int degrees) {
Optional<Integer> opt = Optional.ofNullable(degrees);
Direction direction = null;
if(opt.isPresent()) {
Object obj = Integer.valueOf(degrees);
for(Direction dir : Direction.values()) {
if(dir == obj) {
direction = dir;
}
}
}
return direction;
}
}
In every case i get "null" for result. And the other thing that i cant understand is how can i return empty optional when i cant convert from Optional to Direction?
Thanks in andvance.
>Solution :
you’re mixing non optional input argument and optional return, then you’re compaing Direction object with optional – they will never be equal, probably you need something like this:
public static Optional<Direction> ofDegrees(int degrees) {
for (Direction dir : Direction.values()) {
if (dir.degrees == degrees) {
return Optional.of(dir);
}
}
return Optional.empty();
}