But hey, there are no explicit pointers in Java? Anyways, it kind of means that you have, or will in the future have, an object that may or may not be there. Or a method returns an object but it may not. Below is a concept I borrowed from Scala that better reflects optionality.
public void doStuff() {
// returnAStringOrNot returns Some<String> or None
Option<String> aStringOrNot = returnAStringOrNot();
if (aStringOrNot.none()) {
doSomeOtherStuff();
} else {
String aString = aStringOrNot.get();
doSomeGoodStuff(aString);
}
//or similarly
for (String aString : returnAStringOrNot()) {
doSomeGoodStuff(aString);
}
}
private Option<String> returnAStringOrNot() {
return inAGoodDay ? Option.Some("Hello") : Option.<String> None();
}
But what happens if returnAStringOrNot() returns a null?
ReplyDelete@Genius:- you get a NullPointerException when you call none() or get() Genius
ReplyDelete