Created
June 3, 2009 07:14
-
-
Save pcdavid/122836 to your computer and use it in GitHub Desktop.
Optional.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Optional<T> { | |
private final boolean isSet; | |
private final T value; | |
public static <T> Optional<T> nothing() { | |
return new Optional<T>(false, null); | |
} | |
public static <T> Optional<T> value(T value) { | |
return new Optional<T>(true, value); | |
} | |
private Optional(boolean isSet, T value) { | |
this.isSet = isSet; | |
this.value = value; | |
} | |
public boolean isSet() { return isSet; } | |
public T getValue() { return value; } | |
public String toString() { | |
if (!isSet) { | |
return "#<nothing>"; | |
} else { | |
return "#<value: " + String.valueOf(value) + ">"; | |
} | |
} | |
public static void main(String[] args) { | |
System.out.println("Nothing: " + Optional.nothing()); | |
System.out.println("Explicit int: " + Optional.value(42)); | |
System.out.println("Explicit null: " + Optional.value(null)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment