Skip to content

Instantly share code, notes, and snippets.

@notyy
Last active December 22, 2015 05:19
Show Gist options
  • Select an option

  • Save notyy/6423331 to your computer and use it in GitHub Desktop.

Select an option

Save notyy/6423331 to your computer and use it in GitHub Desktop.
Option in java
package notyy;
public class Option<A> {
private final A thing;
public Option(A thing) {
this.thing = thing;
}
public <E extends Exception> A getOrThrow(E excetion) throws E{
if(thing == null){
throw excetion;
}
return thing;
}
public <B extends A> A getOrElse(B another) {
return thing == null ? another : thing;
}
}
package notyy;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class OptionTest {
@org.junit.Test
public void testGetOrThrow() throws Exception {
String rs = new Option<String>("abc").getOrThrow(new IllegalArgumentException("exception"));
assertThat(rs,is("abc"));
try{
new Option<String>(null).getOrThrow(new IllegalArgumentException("exception"));
fail("should throw exception");
} catch (IllegalArgumentException ex){
assertThat(ex.getMessage(),is("exception"));
}
}
@org.junit.Test
public void testGetOrElse() throws Exception {
String rs = new Option<String>("abc").getOrElse("xyz");
assertThat(rs, is("abc"));
assertThat(new Option<String>(null).getOrElse("xyz"),is("xyz"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment