Skip to content

Commit b344258

Browse files
committed
SafeFunction.getUsingDefault()
1 parent e9be50d commit b344258

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- SafeFunction.getUsingDefault()
13+
1014
## [8.6.4] - 2024-07-18
1115

1216
### Fixed

fj-core/src/main/java/org/fugerit/java/core/function/SafeFunction.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,25 @@ public static <T> T getWithDefault( UnsafeSupplier<T, Exception> supplier, Funct
196196
}
197197
return res;
198198
}
199+
200+
/**
201+
* <p>Return the value provided by the supplier, if null will use the alternative supplier.</p>
202+
*
203+
* @param <T> the return type
204+
* @param supplier the {@link UnsafeSupplier} the return value supplier
205+
* @param altSupplier the alternative {@link UnsafeSupplier} the return value supplier
206+
* @return the value evaluated by the supplier
207+
*/
208+
public static <T> T getUsingDefault( UnsafeSupplier<T, Exception> supplier, UnsafeSupplier<T, Exception> altSupplier ) {
209+
return SafeFunction.get( () -> {
210+
T res = supplier.get();
211+
if ( res != null ) {
212+
return res;
213+
} else {
214+
return altSupplier.get();
215+
}
216+
} );
217+
}
199218

200219
/**
201220
* <p>Apply an UnsafeVoid function, using a consumer the handle any Exception raised.</p>

fj-core/src/test/java/test/org/fugerit/java/core/function/TestSafeFunction.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ public class TestSafeFunction {
2525
private static final DAOException TEST_CHECKED_EX = new DAOException( "test checked" );
2626

2727
private static final DAORuntimeException TEST_RUNTIME_EX = new DAORuntimeException( "test runtime" );
28+
29+
@Test
30+
public void testGetUsingDefault() {
31+
Assert.assertEquals( "2", SafeFunction.getUsingDefault( () -> null, () -> "2" ) );
32+
Assert.assertEquals( "0", SafeFunction.getUsingDefault( () -> "0", () -> "1" ) );
33+
}
2834

2935
@Test
3036
public void testFailGet() {

0 commit comments

Comments
 (0)