Last active
December 22, 2015 05:19
-
-
Save notyy/6423331 to your computer and use it in GitHub Desktop.
Option in java
This file contains hidden or 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
| 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; | |
| } | |
| } |
This file contains hidden or 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
| 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