├── options ├── functions │ ├── .gitignore │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── polanski │ │ └── option │ │ └── function │ │ ├── Function.java │ │ ├── Action.java │ │ ├── Action0.java │ │ ├── Func1.java │ │ ├── Action1.java │ │ ├── FuncN.java │ │ ├── Func2.java │ │ ├── Func3.java │ │ ├── Func4.java │ │ └── Func0.java ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── core │ ├── src │ │ ├── test │ │ │ └── java │ │ │ │ └── polanski │ │ │ │ └── option │ │ │ │ ├── OptionUnsafeTest.kt │ │ │ │ ├── UnitTest.kt │ │ │ │ ├── AtomicOptionTest.kt │ │ │ │ ├── OptionAssertionTest.java │ │ │ │ └── TestOption.kt │ │ └── main │ │ │ └── java │ │ │ └── polanski │ │ │ └── option │ │ │ ├── Unit.java │ │ │ ├── OptionUnsafe.java │ │ │ ├── AtomicOption.java │ │ │ ├── OptionAssertion.java │ │ │ ├── None.java │ │ │ ├── Some.java │ │ │ └── Option.java │ └── build.gradle ├── build.gradle ├── gradle.properties ├── gradlew.bat └── gradlew ├── .gitignore ├── .travis.yml ├── README.md └── LICENSE /options/functions/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /options/functions/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | -------------------------------------------------------------------------------- /options/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':core', ':functions' 2 | -------------------------------------------------------------------------------- /options/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tomaszpolanski/Options/HEAD/options/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Function.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of RxJava Function 5 | */ 6 | public interface Function { 7 | } 8 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Action.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Action from RxJava 5 | */ 6 | public interface Action extends Function { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Action0.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Action0 from RxJava 5 | */ 6 | public interface Action0 extends Action { 7 | 8 | void call(); 9 | } 10 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Func1.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Func1 from RxJava 5 | */ 6 | public interface Func1 extends Function { 7 | 8 | R call(T t); 9 | } 10 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Action1.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Action1 from RxJava 5 | */ 6 | public interface Action1 extends Action { 7 | 8 | void call(T t); 9 | } 10 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/FuncN.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of FuncN from RxJava 5 | */ 6 | public interface FuncN extends Function { 7 | 8 | R call(Object... args); 9 | } 10 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Func2.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Func2 from RxJava 5 | */ 6 | public interface Func2 extends Function { 7 | 8 | R call(T1 t1, T2 t2); 9 | } 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/* 4 | .DS_Store 5 | /build 6 | /options/core/build/ 7 | /captures 8 | /options/local.properties 9 | *.iml 10 | /options/.idea 11 | /options/build/* 12 | /options/core/build/* 13 | /options/build/generated 14 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Func3.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Func3 from RxJava 5 | */ 6 | public interface Func3 extends Function { 7 | 8 | R call(T1 t1, T2 t2, T3 t3); 9 | } 10 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Func4.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | /** 4 | * Copy of Func4 from RxJava 5 | */ 6 | public interface Func4 extends Function { 7 | 8 | R call(T1 t1, T2 t2, T3 t3, T4 t4); 9 | } 10 | -------------------------------------------------------------------------------- /options/core/src/test/java/polanski/option/OptionUnsafeTest.kt: -------------------------------------------------------------------------------- 1 | package polanski.option 2 | 3 | import org.junit.Test 4 | 5 | class OptionUnsafeTest { 6 | 7 | @Test(expected = AssertionError::class) 8 | fun constructor_throwsException() { 9 | OptionUnsafe() 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /options/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat May 14 17:54:43 CEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-all.zip 7 | -------------------------------------------------------------------------------- /options/functions/src/main/java/polanski/option/function/Func0.java: -------------------------------------------------------------------------------- 1 | package polanski.option.function; 2 | 3 | import java.util.concurrent.Callable; 4 | 5 | /** 6 | * Copy of Func0 from RxJava 7 | */ 8 | public interface Func0 extends Function, Callable { 9 | 10 | @Override 11 | R call(); 12 | } 13 | -------------------------------------------------------------------------------- /options/build.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | repositories { 3 | jcenter() 4 | } 5 | ext { 6 | KOTLIN_VERSION = '1.0.6' 7 | } 8 | 9 | tasks.withType(JavaCompile) { 10 | sourceCompatibility = JavaVersion.VERSION_1_6 11 | targetCompatibility = JavaVersion.VERSION_1_6 12 | } 13 | } 14 | 15 | task clean(type: Delete) { 16 | delete rootProject.buildDir 17 | } 18 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | before_cache: 4 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 5 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 6 | cache: 7 | directories: 8 | - $HOME/.gradle/caches/ 9 | - $HOME/.gradle/wrapper/ 10 | 11 | script: 12 | - cd options 13 | - ./gradlew build check 14 | 15 | after_success: 16 | - bash <(curl -s https://codecov.io/bash) 17 | 18 | -------------------------------------------------------------------------------- /options/core/src/test/java/polanski/option/UnitTest.kt: -------------------------------------------------------------------------------- 1 | package polanski.option 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.junit.Test 5 | import org.mockito.Mockito 6 | import org.mockito.Mockito.mock 7 | import polanski.option.Unit.* 8 | import polanski.option.function.Action0 9 | 10 | class UnitTest { 11 | @Test 12 | fun testFrom_returnsUnit() { 13 | assertThat(from(mock(Action0::class.java))).isEqualTo(DEFAULT) 14 | } 15 | 16 | @Test 17 | fun testFrom_callsAction() { 18 | val action = mock(Action0::class.java) 19 | 20 | from(action) 21 | 22 | Mockito.verify(action).call() 23 | } 24 | 25 | @Test 26 | fun testAsUnit_returnsUnit() { 27 | assertThat(asUnit(mock(Any::class.java))).isEqualTo(DEFAULT) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /options/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/Unit.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import polanski.option.function.Action0; 7 | 8 | 9 | /** 10 | * Provides an implementation of a Unit Type. 11 | * 12 | * @see 13 | * https://en.wikipedia.org/wiki/Unit_type 14 | * 15 | */ 16 | public enum Unit { 17 | DEFAULT; 18 | 19 | /** 20 | * Runs an action and returns a unit. 21 | * 22 | * @param action to be executed 23 | * @return Unit 24 | */ 25 | @NotNull 26 | public static Unit from(@NotNull final Action0 action) { 27 | action.call(); 28 | return DEFAULT; 29 | } 30 | 31 | /** 32 | * Ignores an action and returns a unit. 33 | * 34 | * @param ignored to be ignored 35 | * @return Unit 36 | */ 37 | @NotNull 38 | public static Unit asUnit(@Nullable final Object ignored) { 39 | return DEFAULT; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/OptionUnsafe.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | /** 6 | * Helper class allowing unsafe operations on Option 7 | */ 8 | public final class OptionUnsafe { 9 | 10 | OptionUnsafe() { 11 | throw new AssertionError("Must not create an instance"); 12 | } 13 | 14 | /** 15 | * ATTENTION: Only use it when you know what you are doing! 16 | * 17 | * Returns inner value of option if it is Some, otherwise will throw uncatchable exception 18 | * 19 | * @param option Option that will be unwrapped 20 | * @param Wrapped type 21 | * @return Value of Some orResult if None, throws exception 22 | */ 23 | @NotNull 24 | public static T getUnsafe(@NotNull final Option option) { 25 | return option.getUnsafe(); 26 | } 27 | 28 | /** 29 | * ATTENTION: Only use it when you know what you are doing! 30 | * 31 | * Returns inner value of option if it is Some, otherwise will throw give RuntimeException 32 | * 33 | * @param option Option that will be unwrapped 34 | * @param exception Exception to be thrown 35 | * @param Wrapped type 36 | * @return Value of Some orResult if None, throws exception 37 | */ 38 | @NotNull 39 | public static T orThrowUnsafe(@NotNull final Option option, 40 | @NotNull final RuntimeException exception) { 41 | if (option.isSome()) { 42 | return option.getUnsafe(); 43 | } else { 44 | throw exception; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/AtomicOption.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import java.util.concurrent.atomic.AtomicReference; 7 | 8 | import static polanski.option.Option.ofObj; 9 | 10 | /** 11 | * Atomic version of {@link Option}, can be used as final fields in classes. 12 | * 13 | * @param Inner type of Option 14 | */ 15 | public final class AtomicOption extends AtomicReference> { 16 | 17 | /** 18 | * Constructor, the inner value will be set to {@link Option#NONE}. 19 | */ 20 | public AtomicOption() { 21 | super(Option.none()); 22 | } 23 | 24 | /** 25 | * Constructor, if the value is not null, then it will be set, 26 | * otherwise it will be set to {@link Option#NONE}. 27 | * 28 | * @param value Value to be set to the AtomicOption 29 | */ 30 | public AtomicOption(@Nullable final T value) { 31 | super(ofObj(value)); 32 | } 33 | 34 | /** 35 | * Atomically sets the value to None returns the old value. 36 | * 37 | * @return the previous value 38 | */ 39 | @NotNull 40 | public Option getAndClear() { 41 | return getAndSet(Option.none()); 42 | } 43 | 44 | /** 45 | * Replaces the previous value if it was {@link Option#NONE}. 46 | * 47 | * @param value Value to replace {@link Option#NONE} 48 | * @return True if the value was replaces, otherwise false 49 | */ 50 | public boolean setIfNone(@Nullable final T value) { 51 | return compareAndSet(Option.none(), ofObj(value)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /options/core/src/test/java/polanski/option/AtomicOptionTest.kt: -------------------------------------------------------------------------------- 1 | package polanski.option 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.junit.Test 5 | import polanski.option.Option.NONE 6 | import polanski.option.Option.ofObj 7 | 8 | class AtomicOptionTest { 9 | 10 | @Test 11 | fun isNone_byDefault() { 12 | assertThat(AtomicOption().get()).isEqualTo(NONE) 13 | } 14 | 15 | @Test 16 | fun constructor_setsTheValue() { 17 | val str = "Something" 18 | assertThat(AtomicOption(str).get()).isEqualTo(ofObj(str)) 19 | } 20 | 21 | @Test 22 | fun getAndClear_returnsOldValue() { 23 | val str = "Something" 24 | val atomic = AtomicOption(str) 25 | 26 | assertThat(atomic.getAndClear()).isEqualTo(ofObj(str)) 27 | } 28 | 29 | @Test 30 | fun getAndClear_clearsPreviousValue() { 31 | val atomic = AtomicOption("Something") 32 | 33 | atomic.getAndClear() 34 | 35 | assertThat(atomic.get()).isEqualTo(NONE) 36 | } 37 | 38 | @Test 39 | fun setIfNone_whenValueIsNotNone_returnFalse() { 40 | val atomic = AtomicOption("") 41 | 42 | assertThat(atomic.setIfNone("String")).isFalse() 43 | } 44 | 45 | @Test 46 | fun setIfNone_whenValueIsNone_returnTrue() { 47 | val atomic = AtomicOption() 48 | 49 | assertThat(atomic.setIfNone("String")).isTrue() 50 | } 51 | 52 | @Test 53 | fun setIfNone_setsNewValue() { 54 | val newString = "Str" 55 | val atomic = AtomicOption() 56 | atomic.setIfNone(newString) 57 | 58 | assertThat(atomic.get()).isEqualTo(ofObj(newString)) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /options/core/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'kotlin' 3 | apply plugin: 'jacoco' 4 | 5 | group = 'com.github.tomaszpolanski' 6 | 7 | jacocoTestReport { 8 | reports { 9 | xml.enabled = true 10 | html.enabled = true 11 | } 12 | } 13 | 14 | check.dependsOn jacocoTestReport 15 | 16 | buildscript { 17 | repositories { 18 | mavenLocal() 19 | mavenCentral() 20 | jcenter() 21 | 22 | maven { url "http://repo1.maven.org/maven2/" } 23 | } 24 | dependencies { 25 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$project.ext.KOTLIN_VERSION" 26 | } 27 | } 28 | 29 | version = '1.3.0' 30 | 31 | sourceSets { 32 | test.java.srcDirs += 'src/test/kotlin' 33 | } 34 | 35 | afterEvaluate { 36 | sourceSets.all { sourceSet -> 37 | if (!sourceSet.name.startsWith("test")) { 38 | sourceSet.kotlin.setSrcDirs([]) 39 | } 40 | } 41 | } 42 | 43 | dependencies { 44 | compile fileTree(include: ['*.jar'], dir: 'libs') 45 | compile project(':functions') 46 | compile 'org.jetbrains:annotations:13.0' 47 | testCompile 'junit:junit:4.12' 48 | testCompile 'org.mockito:mockito-core:1.10.19' 49 | testCompile "org.jetbrains.kotlin:kotlin-stdlib:1.0.1-2" 50 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:1.0.0" 51 | testCompile('org.assertj:assertj-core:1.7.1') 52 | } 53 | 54 | // build a jar with source files 55 | task sourcesJar(type: Jar) { 56 | from sourceSets.main.java.srcDirs 57 | classifier = 'sources' 58 | } 59 | 60 | // build a jar with javadoc 61 | task javadocJar(type: Jar, dependsOn: javadoc) { 62 | classifier = 'javadoc' 63 | from javadoc.destinationDir 64 | } 65 | 66 | artifacts { 67 | archives sourcesJar 68 | archives javadocJar 69 | } 70 | -------------------------------------------------------------------------------- /options/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Options 3 | [![Build Status](https://travis-ci.org/tomaszpolanski/Options.svg?branch=master)](https://travis-ci.org/tomaszpolanski/Options) 4 | [![codecov.io](http://codecov.io/github/tomaszpolanski/Options/coverage.svg?branch=master)](http://codecov.io/github/tomaszpolanski/Options?branch=master) 5 | 6 | [Functional Option](https://en.wikipedia.org/wiki/Option_type) that can be used with Java 1.6 and Android. 7 | 8 | ## Option 9 | 10 | Similar to [Java 8 ``Optional``](http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html) but targeting Android and Java 6. 11 | 12 | ### Why to use them? 13 | 14 | In 1965, Sir Tony Hoare introduced ``null`` reference. Since then he apologised for that and called it [The Billion Dollar Mistake](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare). 15 | If the inventor of ``null`` pointers and references has condemned them, why the rest of us should be using them? 16 | 17 | 18 | ### Where to use them? 19 | 20 | Currently there are several ways to say that an object could be null. Most popular way in Android nowadays is using ``Nullable`` or ``NonNull`` annotations. 21 | The problem with those annotations is that you cannot say what kind of objects are in an array, or if you use Rx, in an ``Observable``. 22 | With ``Options`` you can use instead ```List>``` or in Rx ```Observable>```. 23 | 24 | ### How to use them? 25 | If you have been using RxJava, this API will look really similar to RxJava. 26 | Still ``Option`` is synchronous API that does not have too much to do with Reactive Programming. 27 | 28 | **Basic usage** 29 | 30 | Code with ``nulls``: 31 | 32 | ``` Java 33 | String input = ...; 34 | String result = null; 35 | 36 | if (input != null && input.length() > 0) { 37 | result = "Length of the string is " + input.length(); 38 | } else { 39 | result = "The string is null or empty"; 40 | } 41 | ``` 42 | 43 | Code with ``Options``: 44 | 45 | ``` Java 46 | String input = ...; 47 | 48 | String result = Option.ofObj(input) 49 | .filter(str -> str.length() > 0) 50 | .match(str -> "Length of the string is " + str.length(), 51 | () -> "The string is null or empty"); 52 | ``` 53 | 54 | **Advance usage** 55 | 56 | Code with ``nulls``: 57 | 58 | ```Java 59 | String input = ...; 60 | String result = null; 61 | 62 | if (input != null) { 63 | try { 64 | int intValue = Integer.parseInt(input); 65 | result = "Input can be parsed to number: " + intValue; 66 | } catch (NumberFormatException e) { 67 | result = "Input is not a number"; 68 | } 69 | } 70 | ``` 71 | 72 | Code with ``Options``: 73 | 74 | ``` Java 75 | String input = ...; 76 | 77 | String result = Option.ofObj(input) 78 | .flatMap(str -> Option.tryAsOption(() -> Integer.parseInt(str))) 79 | .map(intValue -> "Input can be parsed to number: " + intValue) 80 | .orDefault(() -> "Input is not a number"); 81 | ``` 82 | 83 | ### How to include in your project? 84 | 85 | [![](https://jitpack.io/v/tomaszpolanski/options.svg)](https://jitpack.io/#tomaszpolanski/options) 86 | 87 | Options are available on maven via [jitpack](https://jitpack.io/#tomaszpolanski/options/). Just add to your gradle files: 88 | 89 | To your top level gradle.build file add repository: 90 | ``` Groovy 91 | repositories { 92 | jcenter() 93 | maven { url "https://jitpack.io" } 94 | } 95 | ``` 96 | 97 | To your module level gradle.build add dependency: 98 | ``` Groovy 99 | dependencies { 100 | // other dependencies 101 | implementation 'com.github.tomaszpolanski:options:1.3.0' 102 | } 103 | ``` 104 | 105 | ### Can I use it with Kotlin? 106 | Sure, you can, but I would recommend using Peter Tackage's [kotlin-options](https://github.com/peter-tackage/kotlin-options) as they play nicer with Kotlin. 107 | 108 | ## References 109 | 110 | This library was strongly influenced by [C# Functional Language Extensions](https://github.com/louthy/language-ext). 111 | -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/OptionAssertion.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import java.util.Objects; 4 | 5 | import org.jetbrains.annotations.NotNull; 6 | import org.jetbrains.annotations.Nullable; 7 | import polanski.option.function.Func1; 8 | 9 | /** 10 | * Assertions to test the nature of a wrapped {@link Option}. 11 | */ 12 | public final class OptionAssertion { 13 | 14 | @NotNull 15 | private final Option actual; 16 | 17 | OptionAssertion(@NotNull final Option actual) { 18 | checkNotNull(actual, "Option cannot be null"); 19 | 20 | this.actual = actual; 21 | } 22 | 23 | /** 24 | * Asserts that the {@link Option} is {@link Option#NONE}. 25 | */ 26 | public void assertIsNone() { 27 | if (!actual.isNone()) { 28 | throw fail("Option was not None"); 29 | } 30 | } 31 | 32 | /** 33 | * Asserts that the {@link Option} is {@link Some}. 34 | * 35 | * @return this. 36 | */ 37 | @NotNull 38 | public OptionAssertion assertIsSome() { 39 | if (!actual.isSome()) { 40 | throw fail("Option was not Some"); 41 | } 42 | return this; 43 | } 44 | 45 | /** 46 | * Asserts that the {@link Option} is {@link Some} and that the wrapped value is equal to the 47 | * given value. Equality is determined using {@link Objects#equals(Object, Object)}. 48 | * 49 | * @param expected The expected value. May not be null. 50 | * @return this. 51 | */ 52 | @NotNull 53 | public OptionAssertion assertValue(@NotNull final T expected) { 54 | checkNotNull(expected, "Expected value cannot be null: use assertNone instead"); 55 | 56 | if (!actual.isSome()) { 57 | throw fail("Option was not Some"); 58 | } 59 | 60 | if (!matches(actual, equalsPredicate(expected))) { 61 | throw fail(String.format("Actual Option value: <%s> did not equal expected value: <%s>", 62 | OptionUnsafe.getUnsafe(actual), 63 | expected)); 64 | } 65 | return this; 66 | } 67 | 68 | /** 69 | * Asserts that the {@link Option} is {@link Some} and that the wrapped value matches given 70 | * predicate function. 71 | * 72 | * @param predicate The predicate function. May not be null. 73 | * @return this. 74 | */ 75 | @NotNull 76 | public OptionAssertion assertValue(@NotNull final Func1 predicate) { 77 | checkNotNull(predicate, "Predicate function cannot be null"); 78 | 79 | if (!actual.isSome()) { 80 | throw fail("Option was not Some"); 81 | } 82 | 83 | if (!matches(actual, predicate)) { 84 | throw fail(String.format("Actual Option value: <%s> did not match predicate", actual)); 85 | } 86 | return this; 87 | } 88 | 89 | @NotNull 90 | private static Func1 equalsPredicate(@NotNull final T expected) { 91 | return new Func1() { 92 | @Override 93 | public Boolean call(final T t) { 94 | return Objects.equals(t, expected); 95 | } 96 | }; 97 | } 98 | 99 | private static boolean matches(@NotNull final Option actual, 100 | @NotNull final Func1 predicate) { 101 | return actual.filter(predicate).isSome(); 102 | } 103 | 104 | @NotNull 105 | private AssertionError fail(@Nullable final String message) { 106 | StringBuilder b = new StringBuilder(); 107 | b.append(message); 108 | 109 | b.append(" (") 110 | .append("Actual = ").append(actual.toString()) 111 | .append(')'); 112 | 113 | return new AssertionError(b.toString()); 114 | } 115 | 116 | private static void checkNotNull(@Nullable final T value, 117 | @NotNull final String msg) { 118 | if (value == null) { 119 | throw new IllegalArgumentException(msg); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/None.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import java.util.List; 7 | 8 | import polanski.option.function.Action0; 9 | import polanski.option.function.Action1; 10 | import polanski.option.function.Func0; 11 | import polanski.option.function.Func1; 12 | import polanski.option.function.Func2; 13 | import polanski.option.function.Func3; 14 | import polanski.option.function.Func4; 15 | import polanski.option.function.FuncN; 16 | 17 | /** 18 | * Represent missing value 19 | * 20 | * @param Type of missing value 21 | */ 22 | public final class None extends Option { 23 | 24 | None() { 25 | } 26 | 27 | @Override 28 | public boolean isSome() { 29 | return false; 30 | } 31 | 32 | @Override 33 | public boolean isNone() { 34 | return true; 35 | } 36 | 37 | @Override 38 | public Option ifSome(@NotNull final Action1 action) { 39 | // Do nothing 40 | return this; 41 | } 42 | 43 | @Override 44 | public Option ifNone(@NotNull final Action0 action) { 45 | action.call(); 46 | return this; 47 | } 48 | 49 | @NotNull 50 | @Override 51 | public Option map(@NotNull final Func1 f) { 52 | return none(); 53 | } 54 | 55 | @NotNull 56 | @Override 57 | public Option flatMap(@NotNull final Func1> f) { 58 | return none(); 59 | } 60 | 61 | @NotNull 62 | @Override 63 | public Option filter(@NotNull final Func1 predicate) { 64 | return none(); 65 | } 66 | 67 | @NotNull 68 | @Override 69 | public Option orOption(@NotNull final Func0> f) { 70 | return f.call(); 71 | } 72 | 73 | @NotNull 74 | @Override 75 | public T orDefault(@NotNull final Func0 def) { 76 | return def.call(); 77 | } 78 | 79 | @NotNull 80 | @Override 81 | T getUnsafe() { 82 | throw new IllegalStateException(); 83 | } 84 | 85 | @NotNull 86 | @Override 87 | public Option ofType(@NotNull Class type) { 88 | return none(); 89 | } 90 | 91 | @NotNull 92 | @Override 93 | public OUT match(@NotNull Func1 fSome, 94 | @NotNull Func0 fNone) { 95 | return fNone.call(); 96 | } 97 | 98 | @NotNull 99 | @Override 100 | public polanski.option.Unit matchAction(@NotNull Action1 fSome, @NotNull Action0 fNone) { 101 | return polanski.option.Unit.from(fNone); 102 | } 103 | 104 | @Nullable 105 | @Override 106 | public OUT matchUnsafe(@NotNull Func1 fSome, @NotNull Func0 fNone) { 107 | return fNone.call(); 108 | } 109 | 110 | @NotNull 111 | @Override 112 | public Option lift(@NotNull final Option optionB, 113 | @NotNull final Func2 f) { 114 | return none(); 115 | } 116 | 117 | @NotNull 118 | @Override 119 | public Option lift(@NotNull Option option1, 120 | @NotNull Option option2, 121 | @NotNull Func3 f) { 122 | return none(); 123 | } 124 | 125 | @NotNull 126 | @Override 127 | public Option lift(@NotNull Option option1, 128 | @NotNull Option option2, 129 | @NotNull Option option3, 130 | @NotNull Func4 f) { 131 | return none(); 132 | } 133 | 134 | @NotNull 135 | @Override 136 | public Option lift(@NotNull final List> options, 137 | @NotNull final FuncN f) { 138 | return none(); 139 | } 140 | 141 | @Override 142 | public String toString() { 143 | return getClass().getSimpleName(); 144 | } 145 | 146 | @Override 147 | public int hashCode() { 148 | return 0; 149 | } 150 | 151 | @Override 152 | public boolean equals(final Object o) { 153 | return o instanceof None; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /options/core/src/test/java/polanski/option/OptionAssertionTest.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.junit.Rule; 4 | import org.junit.Test; 5 | import org.junit.rules.ExpectedException; 6 | 7 | import polanski.option.function.Func1; 8 | 9 | import static org.hamcrest.CoreMatchers.startsWith; 10 | 11 | public class OptionAssertionTest { 12 | 13 | @Rule 14 | public ExpectedException thrown = ExpectedException.none(); 15 | 16 | // assertIsNone 17 | 18 | @Test 19 | public void assertIsNone_doesNotThrowAssertionError_whenNone() { 20 | new OptionAssertion(Option.none()).assertIsNone(); 21 | } 22 | 23 | @Test 24 | public void assertIsNone_throwAssertionError_whenSome() { 25 | thrown.expect(AssertionError.class); 26 | thrown.expectMessage(startsWith("Option was not None")); 27 | 28 | new OptionAssertion(Option.ofObj("value")).assertIsNone(); 29 | } 30 | 31 | // assertIsSome 32 | 33 | @Test 34 | public void assertIsSome_doesNotThrowAssertionError_whenSome() { 35 | new OptionAssertion(Option.ofObj("value")).assertIsSome(); 36 | } 37 | 38 | @Test 39 | public void assertIsSome_throwsAssertionError_whenNone() { 40 | thrown.expect(AssertionError.class); 41 | thrown.expectMessage(startsWith("Option was not Some")); 42 | 43 | new OptionAssertion(Option.none()).assertIsSome(); 44 | } 45 | 46 | // assertValue (predicate) 47 | 48 | @Test 49 | public void assertValue_doesNotThrowAssertionError_whenPredicateTrue() { 50 | final String expected = "value"; 51 | new OptionAssertion(Option.ofObj("value")) 52 | .assertValue(new Func1() { 53 | @Override 54 | public Boolean call(final String actualValue) { 55 | return actualValue.equals(expected); 56 | } 57 | }); 58 | } 59 | 60 | @Test 61 | public void assertValue_throwsAssertionError_whenPredicateFalse() { 62 | thrown.expect(AssertionError.class); 63 | thrown.expectMessage(startsWith("Actual Option value: did not match predicate")); 64 | 65 | new OptionAssertion(Option.ofObj("value")) 66 | .assertValue(new Func1() { 67 | @Override 68 | public Boolean call(final String actualValue) { 69 | return actualValue.equals("different"); 70 | } 71 | }); 72 | } 73 | 74 | @Test 75 | public void assertValue_throwsAssertionError_whenOptionNone() { 76 | thrown.expect(AssertionError.class); 77 | thrown.expectMessage(startsWith("Option was not Some")); 78 | 79 | new OptionAssertion(Option.none()) 80 | .assertValue(new Func1() { 81 | @Override 82 | public Boolean call(final Object actualValue) { 83 | return actualValue.equals("expected"); 84 | } 85 | }); 86 | } 87 | 88 | // assertValue (equals) 89 | 90 | @Test 91 | public void assertValue_doesNotThrowAssertionError_whenEqualTo() { 92 | String actual = "value"; 93 | String expected = "value"; 94 | new OptionAssertion(Option.ofObj(actual)) 95 | .assertValue(expected); 96 | } 97 | 98 | @Test 99 | public void assertValue_throwsAssertionError_whenNotEqualTo() { 100 | thrown.expect(AssertionError.class); 101 | thrown.expectMessage( 102 | startsWith( 103 | "Actual Option value: did not equal expected value: ")); 104 | 105 | String actual = "actual"; 106 | 107 | new OptionAssertion(Option.ofObj(actual)) 108 | .assertValue("expected"); 109 | } 110 | 111 | @Test 112 | public void assertValue_throwsAssertionError_whenOptionNone_notEqualTo() { 113 | thrown.expect(AssertionError.class); 114 | thrown.expectMessage(startsWith("Option was not Some")); 115 | 116 | new OptionAssertion(Option.none()) 117 | .assertValue("expected"); 118 | } 119 | 120 | // Preconditions 121 | 122 | @Test 123 | public void constructor_prohibitNull() { 124 | thrown.expect(IllegalArgumentException.class); 125 | thrown.expectMessage(startsWith("Option cannot be null")); 126 | 127 | //noinspection ConstantConditions 128 | new OptionAssertion(null); 129 | } 130 | 131 | @Test 132 | public void assertValue_prohibitsNullValue() { 133 | thrown.expect(IllegalArgumentException.class); 134 | thrown.expectMessage(startsWith("Expected value cannot be null: use assertNone instead")); 135 | 136 | //noinspection ConstantConditions 137 | new OptionAssertion(Option.none()) 138 | .assertValue((Object) null); 139 | } 140 | 141 | @Test 142 | public void assertValue_prohibitsNullPredicateFunction() { 143 | thrown.expect(IllegalArgumentException.class); 144 | thrown.expectMessage(startsWith("Predicate function cannot be null")); 145 | 146 | //noinspection ConstantConditions 147 | new OptionAssertion(Option.none()) 148 | .assertValue(null); 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /options/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/Some.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import java.util.List; 7 | 8 | import polanski.option.function.Action0; 9 | import polanski.option.function.Action1; 10 | import polanski.option.function.Func0; 11 | import polanski.option.function.Func1; 12 | import polanski.option.function.Func2; 13 | import polanski.option.function.Func3; 14 | import polanski.option.function.Func4; 15 | import polanski.option.function.FuncN; 16 | 17 | import static polanski.option.Unit.from; 18 | 19 | /** 20 | * Represent option of existing value. 21 | * 22 | * @param type of object that exists 23 | */ 24 | public final class Some extends Option { 25 | 26 | @NotNull 27 | private final T mValue; 28 | 29 | Some(@NotNull final T value) { 30 | mValue = value; 31 | } 32 | 33 | @Override 34 | public boolean isSome() { 35 | return true; 36 | } 37 | 38 | @Override 39 | public boolean isNone() { 40 | return false; 41 | } 42 | 43 | @Override 44 | public Option ifSome(@NotNull final Action1 action) { 45 | action.call(mValue); 46 | return this; 47 | } 48 | 49 | @Override 50 | public Option ifNone(@NotNull final Action0 action) { 51 | // Do nothing 52 | return this; 53 | } 54 | 55 | @NotNull 56 | @Override 57 | public Option map(@NotNull final Func1 f) { 58 | return ofObj(f.call(mValue)); 59 | } 60 | 61 | @NotNull 62 | @Override 63 | public Option flatMap(@NotNull final Func1> f) { 64 | return f.call(mValue); 65 | } 66 | 67 | @NotNull 68 | @Override 69 | public Option filter(@NotNull final Func1 predicate) { 70 | return predicate.call(mValue) ? this : Option.none(); 71 | } 72 | 73 | @NotNull 74 | @Override 75 | public Option orOption(@NotNull final Func0> f) { 76 | return this; 77 | } 78 | 79 | @NotNull 80 | @Override 81 | public T orDefault(@NotNull final Func0 def) { 82 | return mValue; 83 | } 84 | 85 | @NotNull 86 | @Override 87 | T getUnsafe() { 88 | return mValue; 89 | } 90 | 91 | @NotNull 92 | @Override 93 | public Option ofType(@NotNull final Class type) { 94 | return type.isInstance(mValue) ? ofObj(type.cast(mValue)) : Option.none(); 95 | } 96 | 97 | @NotNull 98 | @Override 99 | public OUT match(@NotNull final Func1 fSome, 100 | @NotNull final Func0 fNone) { 101 | return fSome.call(mValue); 102 | } 103 | 104 | @NotNull 105 | @Override 106 | public polanski.option.Unit matchAction(@NotNull final Action1 fSome, 107 | @NotNull final Action0 fNone) { 108 | return from(new Action0() { 109 | @Override 110 | public void call() { 111 | fSome.call(mValue); 112 | } 113 | }); 114 | } 115 | 116 | @Nullable 117 | @Override 118 | public OUT matchUnsafe(@NotNull Func1 fSome, @NotNull Func0 fNone) { 119 | return fSome.call(mValue); 120 | } 121 | 122 | @NotNull 123 | @Override 124 | public Option lift(@NotNull final Option option, 125 | @NotNull final Func2 f) { 126 | return option.map(new Func1() { 127 | @Override 128 | public OUT2 call(final IN b) { 129 | return f.call(mValue, b); 130 | } 131 | }); 132 | } 133 | 134 | @NotNull 135 | @Override 136 | public Option lift(@NotNull final Option option1, 137 | @NotNull final Option option2, 138 | @NotNull final Func3 f) { 139 | return option1.lift(option2, new Func2() { 140 | @Override 141 | public OUT call(final IN1 o1, final IN2 o2) { 142 | return f.call(mValue, o1, o2); 143 | } 144 | }); 145 | } 146 | 147 | @NotNull 148 | @Override 149 | public Option lift(@NotNull final Option option1, 150 | @NotNull final Option option2, 151 | @NotNull final Option option3, 152 | @NotNull final Func4 f) { 153 | return option1.lift(option2, option3, new Func3() { 154 | @Override 155 | public OUT call(final IN1 o1, final IN2 o2, final IN3 o3) { 156 | return f.call(mValue, o1, o2, o3); 157 | } 158 | }); 159 | } 160 | 161 | @NotNull 162 | @Override 163 | public Option lift(@NotNull final List> options, 164 | @NotNull final FuncN f) { 165 | 166 | return options.size() == 1 167 | ? first(options).map(new Func1() { 168 | @Override 169 | public OUT call(final IN it) { 170 | return f.call(it, mValue); 171 | } 172 | }) 173 | : first(options).lift(tail(options), 174 | new FuncN() { 175 | @Override 176 | public OUT call(final Object... list) { 177 | return f.call(combine(mValue, list)); 178 | } 179 | }); 180 | } 181 | 182 | @NotNull 183 | private static T first(@NotNull final List options) { 184 | return options.get(0); 185 | } 186 | 187 | @NotNull 188 | private static List tail(@NotNull final List options) { 189 | return options.subList(1, options.size()); 190 | } 191 | 192 | @NotNull 193 | private static Object[] combine(@NotNull final Object[] a, @NotNull final Object[] b) { 194 | final int length = a.length + b.length; 195 | Object[] result = new Object[length]; 196 | System.arraycopy(a, 0, result, 0, a.length); 197 | System.arraycopy(b, 0, result, a.length, b.length); 198 | return result; 199 | } 200 | 201 | @NotNull 202 | private static Object[] combine(@NotNull final Object a, @NotNull final Object[] b) { 203 | return combine(new Object[]{a}, b); 204 | } 205 | 206 | @Override 207 | public int hashCode() { 208 | return mValue.hashCode(); 209 | } 210 | 211 | @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") 212 | @Override 213 | public boolean equals(final Object o) { 214 | return ofObj(o) 215 | .ofType(Some.class) 216 | .filter(new Func1() { 217 | @Override 218 | public Boolean call(final Some some) { 219 | return some.getUnsafe().equals(mValue); 220 | } 221 | }) != NONE; 222 | } 223 | 224 | @Override 225 | public String toString() { 226 | return mValue.toString(); 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /options/core/src/main/java/polanski/option/Option.java: -------------------------------------------------------------------------------- 1 | package polanski.option; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import java.util.List; 7 | import java.util.concurrent.Callable; 8 | 9 | import polanski.option.function.Action0; 10 | import polanski.option.function.Action1; 11 | import polanski.option.function.Func0; 12 | import polanski.option.function.Func1; 13 | import polanski.option.function.Func2; 14 | import polanski.option.function.Func3; 15 | import polanski.option.function.Func4; 16 | import polanski.option.function.FuncN; 17 | 18 | /** 19 | * Represent possibility of value not existing, 20 | * which needs to be unwrapped before using 21 | * 22 | * @param type of object that could possibly be missing 23 | */ 24 | public abstract class Option { 25 | 26 | /** 27 | * Representation of non existing value 28 | */ 29 | @NotNull 30 | public static final None NONE = new None(); 31 | 32 | /** 33 | * Returns of non existing value without getting unchecked warning 34 | * 35 | * @param Type wrapped in {@link Option} 36 | * @return NONE 37 | */ 38 | @SuppressWarnings("unchecked") 39 | @NotNull 40 | public static Option none() { 41 | return NONE; 42 | } 43 | 44 | /** 45 | * Indicates if option contains value 46 | * 47 | * @return true if Option is Some, otherwise false 48 | */ 49 | public abstract boolean isSome(); 50 | 51 | /** 52 | * Indicates if option does not contain a value 53 | * 54 | * @return true if Option is None, otherwise false 55 | */ 56 | public abstract boolean isNone(); 57 | 58 | /** 59 | * Runs the action on Option value if exists, otherwise does nothing 60 | * 61 | * @param action Action that is called on the inner value 62 | * @return this {@link Option} 63 | */ 64 | public abstract Option ifSome(@NotNull final Action1 action); 65 | 66 | /** 67 | * Runs the action on Option value if does not exist, otherwise does nothing 68 | * 69 | * @param action Action that is called 70 | * @return this {@link Option} 71 | */ 72 | public abstract Option ifNone(@NotNull final Action0 action); 73 | 74 | /** 75 | * Converts inner value with @selector if value exists, otherwise does nothing 76 | * 77 | * @param selector Function that converts inner value 78 | * @param Result type 79 | * @return If value exists, returns converted value otherwise does nothing 80 | */ 81 | @NotNull 82 | public abstract Option map(@NotNull final Func1 selector); 83 | 84 | /** 85 | * Binds option to another option 86 | * 87 | * @param selector Function that returns option to be bound to 88 | * @param Result type 89 | * @return Bound option 90 | */ 91 | @NotNull 92 | public abstract Option flatMap(@NotNull final Func1> selector); 93 | 94 | /** 95 | * Filters options fulfilling given @predicate 96 | * 97 | * @param predicate Function returning true if the parameter should be included 98 | * @return Some if the value checks the condition, otherwise None 99 | */ 100 | @NotNull 101 | public abstract Option filter(@NotNull final Func1 predicate); 102 | 103 | /** 104 | * Returns option if current value is None 105 | * 106 | * @param f Function returning new Option 107 | * @return Option given by the function if current is None, otherwise returns current one 108 | */ 109 | @NotNull 110 | public abstract Option orOption(@NotNull final Func0> f); 111 | 112 | /** 113 | * Returns current inner value if it exists, otherwise the value supplied by @def 114 | * 115 | * @param def Function that returns default value 116 | * @return If value exists, then returns it, otherwise the default 117 | */ 118 | @NotNull 119 | public abstract T orDefault(@NotNull final Func0 def); 120 | 121 | /** 122 | * Forcefully tries to unwrap the inner value. 123 | *

124 | * Caution! Use this value only in special, justified cases! 125 | * Use @match instead. 126 | * 127 | * @return Value if exists, otherwise throws exception that shouldn't be caught 128 | */ 129 | @NotNull 130 | abstract T getUnsafe(); 131 | 132 | /** 133 | * Casts the inner value to given type 134 | * 135 | * @param type Class of the new object 136 | * @param Type the value should be cast to 137 | * @return Option of inner value cast to the OUT, if not possible, then None 138 | */ 139 | @NotNull 140 | public abstract Option ofType(@NotNull final Class type); 141 | 142 | /** 143 | * Option created from given @value 144 | * 145 | * @param value Value that should be wrapped in an Option 146 | * @param Input type 147 | * @return Some of the @value if it is not null, otherwise None 148 | */ 149 | @SuppressWarnings("unchecked") 150 | @NotNull 151 | public static Option ofObj(@Nullable final IN value) { 152 | return value == null ? Option.NONE : new Some(value); 153 | } 154 | 155 | /** 156 | * Option of value returned by the callable function 157 | * 158 | * @param c Function that returns a value, that function could throw an exception 159 | * @param Result type 160 | * @return Option of a value returned by @c, if @c threw an exception, then returns None 161 | */ 162 | @NotNull 163 | public static Option tryAsOption(@NotNull final Callable c) { 164 | try { 165 | return Option.ofObj(c.call()); 166 | } catch (Exception e) { 167 | return none(); 168 | } 169 | } 170 | 171 | /** 172 | * Matches current optional to Some or None and returns appropriate value 173 | * 174 | * @param fSome Function that will be called if value exists 175 | * @param fNone Function that will be called if value does not exist 176 | * @param Result type 177 | * @return Value returned by either @fSome of @fNone 178 | */ 179 | @NotNull 180 | public abstract OUT match(@NotNull final Func1 fSome, 181 | @NotNull final Func0 fNone); 182 | 183 | /** 184 | * Matches current option to Some or None and returns unit 185 | * 186 | * @param fSome Action that will be called if value exists 187 | * @param fNone Action that will be called if value does not exist 188 | * @return Unit 189 | */ 190 | @NotNull 191 | public abstract Unit matchAction(@NotNull final Action1 fSome, 192 | @NotNull final Action0 fNone); 193 | 194 | /** 195 | * Matches current optional to Some orResult None and returns appropriate value 196 | * 197 | * @param fSome Function that will be called if value exists 198 | * @param fNone Function that will be called if value does not exist 199 | * @param Result type 200 | * @return Value returned by either @fSome of @fNone 201 | */ 202 | @Nullable 203 | public abstract OUT matchUnsafe(@NotNull final Func1 fSome, 204 | @NotNull final Func0 fNone); 205 | 206 | /** 207 | * Identity function 208 | * 209 | * @return Current option 210 | */ 211 | @NotNull 212 | public Option id() { 213 | return this; 214 | } 215 | 216 | /** 217 | * Combines given Options using @f 218 | * 219 | * @param option1 Option that should be combined with current option 220 | * @param f Function that combines all inner values of the options into one value 221 | * @param Input type 222 | * @param Result type 223 | * @return Option of some if all the Options were Some, otherwise None 224 | */ 225 | @NotNull 226 | public abstract Option lift(@NotNull final Option option1, 227 | @NotNull final Func2 f); 228 | 229 | /** 230 | * Combines given Options using @f 231 | * 232 | * @param option1 Option that should be combined with current option 233 | * @param option2 Option that should be combined with current option 234 | * @param f Function that combines all inner values of the options into one value 235 | * @param Input type 236 | * @param Input type 237 | * @param Result type 238 | * @return Option of some if all the Options were Some, otherwise None 239 | */ 240 | @NotNull 241 | public abstract Option lift(@NotNull final Option option1, 242 | @NotNull final Option option2, 243 | @NotNull final Func3 f); 244 | 245 | /** 246 | * Combines given Options using @f 247 | * 248 | * @param option1 Option that should be combined with current option 249 | * @param option2 Option that should be combined with current option 250 | * @param option3 Option that should be combined with current option 251 | * @param f Function that combines all inner values of the options into one value 252 | * @param Input type 253 | * @param Input type 254 | * @param Input type 255 | * @param Result type 256 | * @return Option of some if all the Options were Some, otherwise None 257 | */ 258 | @NotNull 259 | public abstract Option lift(@NotNull final Option option1, 260 | @NotNull final Option option2, 261 | @NotNull final Option option3, 262 | @NotNull final Func4 f); 263 | 264 | /** 265 | * Combines given Options using @f. 266 | * 267 | * @param options Options that should be combined with current option 268 | * @param f Function that combines all inner values of the options into one value 269 | * @param Input type 270 | * @param Result type 271 | * @return Option of some if all the Options were Some, otherwise None 272 | */ 273 | @NotNull 274 | public abstract Option lift( 275 | @NotNull final List> options, 276 | @NotNull final FuncN f); 277 | 278 | /** 279 | * Logs the value of the Option via given logging function. 280 | * 281 | * @param logging Logging function 282 | * @return Unchanged option 283 | */ 284 | @NotNull 285 | public Option log(@NotNull final Action1 logging) { 286 | return log("", logging); 287 | } 288 | 289 | /** 290 | * Logs the value of the Option via given logging function. 291 | * 292 | * @param tag Text to be prepended to the logging 293 | * @param logging Logging function 294 | * @return Unchanged option 295 | */ 296 | @NotNull 297 | public Option log(@NotNull String tag, 298 | @NotNull final Action1 logging) { 299 | logging.call(tag.isEmpty() 300 | ? this.toString() 301 | : String.format("%s: %s", tag, this)); 302 | return this; 303 | } 304 | 305 | /** 306 | * Creates a {@link OptionAssertion} from this Option to provide set of assertions for testing. 307 | * 308 | * @return the new {@link OptionAssertion} instance. 309 | */ 310 | @NotNull 311 | public OptionAssertion test() { 312 | return new OptionAssertion(this); 313 | } 314 | 315 | } 316 | 317 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Tomasz Polanski 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /options/core/src/test/java/polanski/option/TestOption.kt: -------------------------------------------------------------------------------- 1 | package polanski.option 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.junit.Assert.* 5 | import org.junit.Test 6 | import org.mockito.Matchers.anyString 7 | import org.mockito.Mockito.* 8 | import polanski.option.Option.* 9 | import polanski.option.OptionUnsafe.getUnsafe 10 | import polanski.option.function.Func2 11 | import polanski.option.function.Func3 12 | import polanski.option.function.Func4 13 | 14 | class TestOption { 15 | 16 | val fun2 = Func2 { f, s -> f + s } 17 | val fun3 = Func3 { f, s, t -> f + s + t } 18 | val fun4 = Func4 { f, s, t, fo -> f + s + t + fo } 19 | 20 | @Test 21 | fun testOfObj_whenSome() { 22 | val str = "Something" 23 | val op = ofObj(str) 24 | 25 | assertThat(op.isSome).isTrue() 26 | assertEquals(str, getUnsafe(op)) 27 | } 28 | 29 | @Test 30 | fun testOfObj_whenNone() { 31 | val str: String? = null 32 | val op = ofObj(str) 33 | 34 | assertThat(op.isSome).isFalse() 35 | } 36 | 37 | @Test 38 | fun testIsSome_whenSome() { 39 | val op = ofObj("Something") 40 | 41 | assertThat(op.isSome).isTrue() 42 | } 43 | 44 | @Test 45 | fun testIsSome_whenNone() { 46 | val op = none() 47 | 48 | assertThat(op.isSome).isFalse() 49 | } 50 | 51 | @Test 52 | fun testIsNone_whenSome() { 53 | val op = ofObj("Something") 54 | 55 | assertThat(op.isNone).isFalse() 56 | } 57 | 58 | @Test 59 | fun testIsNone_whenNone() { 60 | val op = none() 61 | 62 | assertThat(op.isNone).isTrue() 63 | } 64 | 65 | @Test 66 | fun testMap_whenSome() { 67 | val str = "Something" 68 | val op = ofObj("").map { str } 69 | 70 | assertThat(op.isSome).isTrue() 71 | assertEquals(str, getUnsafe(op)) 72 | } 73 | 74 | @Test 75 | fun testMap_whenNone() { 76 | val op = none().map { "" } 77 | 78 | assertThat(op.isSome).isFalse() 79 | } 80 | 81 | @Test 82 | fun testFilter_whenSome() { 83 | val str = "Something" 84 | val op = ofObj(str).filter { it == str } 85 | 86 | assertThat(op.isSome).isTrue() 87 | assertEquals(str, getUnsafe(op)) 88 | } 89 | 90 | @Test 91 | fun testFilterSome_whenFailed() { 92 | val str = "Something" 93 | val op = ofObj(str).filter { it == "" } 94 | 95 | assertThat(op.isSome).isFalse() 96 | } 97 | 98 | @Test 99 | fun testFilter_whenNone() { 100 | val op = none().filter { it == "" } 101 | 102 | assertThat(op.isSome).isFalse() 103 | } 104 | 105 | @Test 106 | fun testFlatMap_whenSome() { 107 | val str = "Something" 108 | val op = ofObj("").flatMap { ofObj(str) } 109 | 110 | assertThat(op.isSome).isTrue() 111 | assertEquals(str, getUnsafe(op)) 112 | } 113 | 114 | @Test 115 | fun testFlatMapSome_whenFailed() { 116 | val op = ofObj("Something").flatMap { none() } 117 | 118 | assertThat(op.isSome).isFalse() 119 | } 120 | 121 | @Test 122 | fun testFlatMap_whenNone() { 123 | val op = none().flatMap { ofObj("") } 124 | 125 | assertThat(op.isSome).isFalse() 126 | } 127 | 128 | @Test 129 | fun testOrOption_whenSome() { 130 | val str = "Something" 131 | val op = ofObj(str).orOption { ofObj("") } 132 | 133 | assertThat(op.isSome).isTrue() 134 | assertEquals(str, getUnsafe(op)) 135 | } 136 | 137 | @Test 138 | fun testOrOption_whenNone() { 139 | val str = "Something" 140 | val op = none().orOption { ofObj(str) } 141 | 142 | assertThat(op.isSome).isTrue() 143 | assertEquals(str, getUnsafe(op)) 144 | } 145 | 146 | @Test 147 | fun testOrDefault_whenSome() { 148 | val str = "Something" 149 | val s = ofObj(str).orDefault { "" } 150 | 151 | assertEquals(str, s) 152 | } 153 | 154 | @Test 155 | fun testOrDefault_whenNone() { 156 | val str = "Something" 157 | val s = none().orDefault { str } 158 | 159 | assertEquals(str, s) 160 | } 161 | 162 | @Test 163 | fun testTryAsOption_whenSome() { 164 | val str = "Something" 165 | val op = tryAsOption { str } 166 | 167 | assertThat(op.isSome).isTrue() 168 | assertEquals(str, getUnsafe(op)) 169 | } 170 | 171 | @Test 172 | fun testTryAsOption_whenNone() { 173 | val str: Int? = null 174 | 175 | val op = tryAsOption { str!!.toString() } 176 | 177 | assertFalse(op.isSome) 178 | } 179 | 180 | @Test 181 | fun testMatchAction_whenSome() { 182 | val someFun = mock(IFunction::class.java) 183 | val noneFun = mock(IFunction::class.java) 184 | 185 | ofObj("").matchAction({ someFun.`fun`() }) 186 | { noneFun.`fun`() } 187 | 188 | verify(someFun).`fun`() 189 | verify(noneFun, never()).`fun`() 190 | } 191 | 192 | @Test 193 | fun testMatchAction_whenNone() { 194 | val someFun = mock(IFunction::class.java) 195 | val noneFun = mock(IFunction::class.java) 196 | 197 | NONE.matchAction( 198 | { someFun.`fun`() } 199 | , { noneFun.`fun`() }) 200 | 201 | verify(someFun, never()).`fun`() 202 | verify(noneFun).`fun`() 203 | } 204 | 205 | @Test 206 | fun testId() { 207 | val op = ofObj("") 208 | 209 | assertEquals(op, op.id()) 210 | } 211 | 212 | @Test 213 | fun testIfSome_whenSome() { 214 | val someFun = mock(IFunction::class.java) 215 | 216 | ofObj("").ifSome { someFun.`fun`() } 217 | 218 | verify(someFun, times(1)).`fun`() 219 | } 220 | 221 | @Test 222 | fun testIfSome_whenNone() { 223 | val noneFun = mock(IFunction::class.java) 224 | 225 | NONE.ifSome { noneFun.`fun`() } 226 | 227 | 228 | verify(noneFun, never()).`fun`() 229 | } 230 | 231 | @Test 232 | fun testIfNone_whenSome() { 233 | val someFun = mock(IFunction::class.java) 234 | 235 | ofObj("").ifNone { someFun.`fun`() } 236 | 237 | verify(someFun, never()).`fun`() 238 | } 239 | 240 | @Test 241 | fun testIfNone_whenNone() { 242 | val noneFun = mock(IFunction::class.java) 243 | 244 | NONE.ifNone { noneFun.`fun`() } 245 | 246 | verify(noneFun, times(1)).`fun`() 247 | } 248 | 249 | @Test 250 | fun testOfType_whenSomeAndProperType() { 251 | val value = "something" 252 | 253 | val op = ofObj(value as Any).ofType(String::class.java) 254 | 255 | assertThat(op.isSome).isTrue() 256 | assertEquals(value, getUnsafe(op)) 257 | } 258 | 259 | @Test 260 | fun testOfType_whenSomeAndInvalidType() { 261 | val value = "something" 262 | 263 | val op = ofObj(value as Any).ofType(Int::class.java) 264 | 265 | assertThat(op.isSome).isFalse() 266 | } 267 | 268 | @Test 269 | fun testOfType_whenNone() { 270 | val op = none().ofType(String::class.java) 271 | 272 | assertThat(op.isSome).isFalse() 273 | } 274 | 275 | @Test 276 | fun testMatch_whenSome() { 277 | val some = "some" 278 | val none = "none" 279 | 280 | val result = ofObj("").match({ some }) 281 | { none } 282 | 283 | assertEquals(some, result) 284 | } 285 | 286 | @Test 287 | fun testMatch_whenNone() { 288 | val none = "none" 289 | 290 | val result = ofObj(null).match({ "some" }) 291 | { none } 292 | 293 | assertEquals(none, result) 294 | } 295 | 296 | @Test 297 | fun testMatchUnsafe_whenSome() { 298 | val some = "some" 299 | 300 | val result = ofObj("").matchUnsafe({ some }) 301 | { "none" } 302 | 303 | assertEquals(some, result) 304 | } 305 | 306 | @Test 307 | fun testMatchUnsafe_whenNone() { 308 | val none = "none" 309 | 310 | val result = ofObj(null).matchUnsafe({ "some" }) 311 | { none } 312 | 313 | assertEquals(none, result) 314 | } 315 | 316 | @Test 317 | fun testLift1_whenAllSome() { 318 | val one = 1 319 | val two = 2 320 | 321 | val op = ofObj(one).lift(ofObj(two), fun2) 322 | 323 | assertThat(op.isSome).isTrue() 324 | assertEquals(fun2.call(one, two), getUnsafe(op)) 325 | } 326 | 327 | @Test 328 | fun testLift1_whenFirstIsNone() { 329 | val op = ofObj(1).lift(none(), fun2) 330 | 331 | assertFalse(op.isSome) 332 | } 333 | 334 | @Test 335 | fun testLift1_whenSecondIsNone() { 336 | val op = none().lift(ofObj(1), fun2) 337 | 338 | assertThat(op.isSome).isFalse() 339 | } 340 | 341 | @Test 342 | fun testLift2_whenAllSome() { 343 | val one = 1 344 | val two = 2 345 | val three = 3 346 | 347 | val op = ofObj(one).lift(ofObj(two), ofObj(three), fun3) 348 | 349 | assertThat(op.isSome).isTrue() 350 | assertEquals(fun3.call(one, two, three), getUnsafe(op)) 351 | } 352 | 353 | @Test 354 | fun testLift2_whenFirstIsNone() { 355 | val op = none().lift(ofObj(1), ofObj(2), fun3) 356 | 357 | assertThat(op.isSome).isFalse() 358 | } 359 | 360 | @Test 361 | fun testLift2_whenSecondIsNone() { 362 | val op = ofObj(1).lift(none(), ofObj(2), fun3) 363 | 364 | assertThat(op.isSome).isFalse() 365 | } 366 | 367 | @Test 368 | fun testLift2_whenThirdIsNone() { 369 | val op = ofObj(1).lift(ofObj(2), none(), fun3) 370 | 371 | assertThat(op.isSome).isFalse() 372 | } 373 | 374 | @Test 375 | fun testLift3_whenAllSome() { 376 | val one = 1 377 | val two = 2 378 | val three = 3 379 | val four = 4 380 | 381 | val op = ofObj(one).lift(ofObj(two), ofObj(three), ofObj(four), fun4) 382 | 383 | assertThat(op.isSome).isTrue() 384 | assertEquals(fun4.call(one, two, three, four), 385 | getUnsafe(op)) 386 | } 387 | 388 | @Test 389 | fun testLift3_whenAnyIsNone() { 390 | val op = ofObj(1).lift(ofObj(2), none(), ofObj(3), fun4) 391 | 392 | assertThat(op.isSome).isFalse() 393 | } 394 | 395 | @Test 396 | fun testLift3_whenFirstIsNone() { 397 | val op = none().lift(ofObj(1), ofObj(2), ofObj(3), fun4) 398 | 399 | assertThat(op.isSome).isFalse() 400 | } 401 | 402 | @Test 403 | fun testLiftMany_whenFirstIsNone_returnNone() { 404 | val op = none().lift(1.rangeTo(4).map { ofObj(it) }, { it }) 405 | 406 | assertThat(op.isSome).isFalse() 407 | } 408 | 409 | @Test 410 | fun testLiftMany_whenAnyIsNone_returnNone() { 411 | val op = ofObj(1).lift(2.rangeTo(4).map { ofObj(it) }.plus(none()), { it }) 412 | 413 | assertThat(op.isSome).isFalse() 414 | } 415 | 416 | @Test 417 | fun testLiftMany_whenAllAreSome_returnSome() { 418 | val funN = polanski.option.function.FuncN { 419 | it.filterIsInstance() 420 | .sum() 421 | } 422 | val first = 1 423 | val rest = 1..4 424 | val op = ofObj(first).lift(rest.map { ofObj(it) }, funN) 425 | 426 | assertThat(op.isSome).isTrue() 427 | assertEquals(rest.sum() + first, getUnsafe(op)) 428 | } 429 | 430 | @Test 431 | fun testToString_whenSome() { 432 | val value = 1 433 | 434 | val result = ofObj(value).toString() 435 | 436 | assertEquals(value.toString(), result) 437 | } 438 | 439 | @Test 440 | fun testToString_whenNone() { 441 | val result = NONE.toString() 442 | 443 | assertEquals(NONE.javaClass.simpleName, result) 444 | } 445 | 446 | @Test 447 | fun testHashCode_whenSome() { 448 | val value = 1 449 | 450 | val result = ofObj(value).hashCode() 451 | 452 | assertEquals(value.hashCode().toLong(), result.toLong()) 453 | } 454 | 455 | @Test 456 | fun testHashCode_whenNone() { 457 | val result = NONE.hashCode() 458 | 459 | assertEquals(0, result.toLong()) 460 | } 461 | 462 | @Test 463 | fun testOrThrowUnsafe_whenSome() { 464 | val value = 1 465 | 466 | val result = OptionUnsafe.orThrowUnsafe(ofObj(value), RuntimeException()) 467 | 468 | assertEquals(value.toLong(), result.toLong()) 469 | } 470 | 471 | @Test(expected = RuntimeException::class) 472 | fun testOrThrowUnsafe_whenNone() { 473 | OptionUnsafe.orThrowUnsafe(NONE, RuntimeException()) 474 | } 475 | 476 | @Test 477 | fun testLog_usesLoggingFunction() { 478 | val loggingFun = mock(IFunction::class.java) 479 | 480 | ofObj("").log { loggingFun.`fun`(it) } 481 | 482 | verify(loggingFun, times(1)).`fun`(anyString()) 483 | } 484 | 485 | @Test 486 | fun testLog_containsValueOfSome() { 487 | val loggingFun = mock(IFunction::class.java) 488 | val option = ofObj("something") 489 | 490 | option.log { loggingFun.`fun`(it) } 491 | 492 | verify(loggingFun, times(1)).`fun`(option.toString()) 493 | } 494 | 495 | @Test 496 | fun testLog_containsNone() { 497 | val option = NONE 498 | val loggingFun = mock(IFunction::class.java) 499 | 500 | option.log { loggingFun.`fun`(it) } 501 | 502 | verify(loggingFun, times(1)).`fun`(option.toString()) 503 | } 504 | 505 | @Test 506 | fun testLog_usesLoggingFunctionWithTag() { 507 | val loggingFun = mock(IFunction::class.java) 508 | 509 | ofObj("").log("") { loggingFun.`fun`(it) } 510 | 511 | verify(loggingFun, times(1)).`fun`(anyString()) 512 | } 513 | 514 | @Test 515 | fun testLog_usesTag() { 516 | val tag = "someTag" 517 | 518 | ofObj("").log(tag) { assertTrue(it.contains(tag)) } 519 | } 520 | 521 | @Test 522 | fun testLog_withTag_containsValueOfSome() { 523 | val option = ofObj("something") 524 | 525 | option.log("any") { assertTrue(it.contains(option.toString())) } 526 | } 527 | 528 | @Test 529 | fun testNone_returnsNONE() { 530 | assertEquals(Option.NONE, Option.none()) 531 | } 532 | 533 | @Test(expected = IllegalStateException::class) 534 | fun testGetUnsafe_none() { 535 | Option.NONE.unsafe 536 | } 537 | 538 | @Test 539 | fun testGetUnsafe_some() { 540 | val value = 1 541 | 542 | assertEquals(value, ofObj(value).unsafe) 543 | } 544 | 545 | @Test 546 | fun testTestOperator_returnsOptionAssertionForGivenOption() { 547 | val value = 1 548 | 549 | ofObj(value).test().assertValue(value) 550 | } 551 | 552 | @Test 553 | fun testEquality() { 554 | val value = ofObj(1) 555 | 556 | assertThat(value).isNotEqualTo(ofObj(2)) 557 | } 558 | 559 | internal interface IFunction { 560 | 561 | fun `fun`() 562 | 563 | fun `fun`(str: String) 564 | } 565 | } 566 | 567 | 568 | --------------------------------------------------------------------------------