I have a piece of code where an interface has an Optional return method and some of the classes that implement it to return something, other don't.
In an effort to embrace this brilliant "null killer", here is what I have tried:
public interface Gun {
public Optional<Bullet> shoot();
}
public class Pistol implements Gun{
@Override
public Optional<Bullet> shoot(){
return Optional.of(this.magazine.remove(0));
}//never mind the check of magazine content
}
public class Bow implements Gun{
@Override
public Optional<Bullet> shoot(){
quill--;
return Optional.empty();
}
}
public class BallisticGelPuddy{
private Gun[] guns = new Gun[]{new Pistol(),new Bow()};
private List<Bullet> bullets = new ArrayList<>();
public void collectBullets(){
//here is the problem
for(Gun gun : guns)
gun.shoot.ifPresent(bullets.add( <the return I got with the method>)
}}
I apologise for how silly this example is.
How can I check the return I just got and add it only if present, using optional?
P.S. is there any real usefulness to Optional which is if(X != null) couldn't do?
Optional
getting assigned anull
value, you know that it's wrong, and may feel justified in fixing it. When you see null getting assigned to another value... well, who knows, maybe that's appropriate. I also feel that, philosophically, "Thing which might be nothing" really should be a different type than "Thing that must be something." It could be done better, but only if it were part of the language from the ground up... and, IMO, Java is about one part pig to three parts lipstick.