File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
main/java/io/vavr/control
test/java/io/vavr/control Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 18
18
*/
19
19
package io .vavr .control ;
20
20
21
+ import io .vavr .CheckedFunction1 ;
21
22
import io .vavr .PartialFunction ;
22
23
import io .vavr .Tuple ;
23
24
import io .vavr .Value ;
@@ -391,6 +392,20 @@ default <U> Option<U> map(Function<? super T, ? extends U> mapper) {
391
392
return isEmpty () ? none () : some (mapper .apply (get ()));
392
393
}
393
394
395
+
396
+ /**
397
+ * Converts this to a {@link Try}, then runs the given checked function if this is a {@link Try.Success},
398
+ * passing the result of the current expression to it.
399
+ *
400
+ * @param <U> The new component type
401
+ * @param mapper A checked function
402
+ * @return a {@code Try}
403
+ * @throws NullPointerException if {@code mapper} is null
404
+ */
405
+ default <U > Try <U > mapTry (CheckedFunction1 <? super T , ? extends U > mapper ) {
406
+ return toTry ().mapTry (mapper );
407
+ }
408
+
394
409
/**
395
410
* Folds either the {@code None} or the {@code Some} side of the Option value.
396
411
*
Original file line number Diff line number Diff line change 25
25
import io .vavr .PartialFunction ;
26
26
import io .vavr .Serializables ;
27
27
import org .junit .jupiter .api .Assertions ;
28
+ import org .junit .jupiter .api .Nested ;
28
29
import org .junit .jupiter .api .Test ;
29
30
30
31
import java .util .*;
@@ -361,6 +362,35 @@ public void shouldMapNone() {
361
362
assertThat (Option .<Integer > none ().map (String ::valueOf )).isEqualTo (Option .none ());
362
363
}
363
364
365
+ @ Nested
366
+ class MapTry {
367
+ @ Test
368
+ public void shouldMapTrySome () {
369
+ assertThat (Option .of (1 ).mapTry (String ::valueOf )).isEqualTo (Try .success ("1" ));
370
+ }
371
+
372
+ @ Test
373
+ public void shouldMapTryNone () {
374
+ Try <String > result = Option .none ().mapTry (String ::valueOf );
375
+ assertThat (result .isFailure ()).isTrue ();
376
+ assertThat (result .getCause ().getClass ()).isEqualTo (NoSuchElementException .class );
377
+ assertThat (result .getCause ().getMessage ()).isEqualTo ("No value present" );
378
+ }
379
+
380
+ @ Test
381
+ public void shouldMapTryCheckedException () {
382
+ Try <Integer > result = Option .of ("a" )
383
+ .mapTry (this ::checkedFunction );
384
+ assertThat (result .isFailure ()).isTrue ();
385
+ assertThat (result .getCause ().getClass ()).isEqualTo (Exception .class );
386
+ assertThat (result .getCause ().getMessage ()).isEqualTo ("message" );
387
+ }
388
+
389
+ private Integer checkedFunction (String string ) throws Exception {
390
+ throw new Exception ("message" );
391
+ }
392
+ }
393
+
364
394
// -- flatMap
365
395
366
396
@ Test
You can’t perform that action at this time.
0 commit comments