Commits

Илья Казначеев committed 3a1782d

Add Option.when(predicate, value): when predicate then Some value else None

Comments (0)

Files changed (2)

src/main/java/ru/yandex/bolts/collection/Option.java

     }
 
     /**
+     * Some if pred, None otherwise.
+     */
+    public static <T> Option<T> when(boolean pred, T x) {
+        if (pred) return some(x);
+        else return none();
+    }
+
+    /**
+     * Some if pred, None otherwise, lazy evaluation.
+     */
+    public static <T> Option<T> when(boolean pred, Function0<T> x) {
+        if (pred) return some(x.apply());
+        else return none();
+    }
+
+    /**
      * Some.
      *
      * @see #some(Object) to create Some instance

src/main/java/ru/yandex/bolts/collection/OptionTest.java

 package ru.yandex.bolts.collection;
 
 import junit.framework.TestCase;
+
 import ru.yandex.bolts.collection.impl.test.SerializationUtils;
 import ru.yandex.bolts.function.Function;
 import ru.yandex.bolts.function.Function0;
         assertSame(n, n.orElse(n));
     }
 
+    public void testWhen() {
+        Option<Integer> s1 = Option.when(true, 1);
+        Option<Integer> s2 = Option.when(false, 2);
+        Option<Integer> s3 = Option.when(s1.isDefined(), Function0.constF(3));;
+        assertEquals(s1, Option.some(1));
+        assertEquals(s2, Option.none());
+        assertEquals(s3, Option.some(3));
+    }
+
     protected Function0 throwFactory() {
         return new Function0<Object>() {
             public Object apply() {