Created
November 21, 2013 21:22
-
-
Save uehaj/7589882 to your computer and use it in GitHub Desktop.
Groovyから簡潔にOptionalを操作する例(an example of handling optional from groovy)
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
| import java.util.Optional | |
| class Java8Groovy { | |
| void test() { | |
| Optional<Integer> firstName = Optional.of("FirstName") | |
| Optional<Integer> lastName = Optional.of("LastName") | |
| Optional NULL = Optional.empty() | |
| assert (lastName + " " + firstName).get() == "LastName FirstName" | |
| assert (NULL + " " + firstName) == NULL | |
| assert (lastName + " " + NULL) == NULL | |
| assert (NULL + " " + NULL) == NULL | |
| } | |
| public static void main(String[] a) { | |
| Optional.metaClass.methodMissing = { String name, Object args -> | |
| assert args instanceof Object[] | |
| for (int i=0; i<args.size(); i++) { | |
| if (args[i] instanceof Optional) { | |
| if (args[i].isPresent()) { | |
| args[i] = args[i].get() | |
| } | |
| else { | |
| return Optional.empty() | |
| } | |
| } | |
| } | |
| if (delegate.isPresent()) { | |
| return Optional.ofNullable(delegate.get().invokeMethod(name, args)) | |
| } | |
| else { | |
| return Optional.empty() | |
| } | |
| } | |
| new Java8Groovy().test(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment