Committed by
Gerrit Code Review
Added a valueOrElse static method to Versioned
Change-Id: Icf6406aca716fd2b427fec52e86f6482ce44f393
Showing
2 changed files
with
22 additions
and
0 deletions
... | @@ -99,6 +99,17 @@ public class Versioned<V> { | ... | @@ -99,6 +99,17 @@ public class Versioned<V> { |
99 | return new Versioned<>(transformer.apply(value), version, creationTime); | 99 | return new Versioned<>(transformer.apply(value), version, creationTime); |
100 | } | 100 | } |
101 | 101 | ||
102 | + /** | ||
103 | + * Returns the value of the specified Versioned object if non-null or else returns | ||
104 | + * a default value. | ||
105 | + * @param versioned versioned object | ||
106 | + * @param defaultValue default value to return if versioned object is null | ||
107 | + * @return versioned value or default value if versioned object is null | ||
108 | + */ | ||
109 | + public static <U> U valueOrElse(Versioned<U> versioned, U defaultValue) { | ||
110 | + return versioned == null ? defaultValue : versioned.value(); | ||
111 | + } | ||
112 | + | ||
102 | @Override | 113 | @Override |
103 | public int hashCode() { | 114 | public int hashCode() { |
104 | return Objects.hashCode(value, version, creationTime); | 115 | return Objects.hashCode(value, version, creationTime); | ... | ... |
... | @@ -60,6 +60,17 @@ public class VersionedTest extends TestCase { | ... | @@ -60,6 +60,17 @@ public class VersionedTest extends TestCase { |
60 | } | 60 | } |
61 | 61 | ||
62 | /** | 62 | /** |
63 | + * Tests the valueOrElse method. | ||
64 | + */ | ||
65 | + @Test | ||
66 | + public void testOrElse() { | ||
67 | + Versioned<String> vv = new Versioned<String>("foo", 1); | ||
68 | + Versioned<String> nullVV = null; | ||
69 | + assertThat(Versioned.valueOrElse(vv, "bar"), is("foo")); | ||
70 | + assertThat(Versioned.valueOrElse(nullVV, "bar"), is("bar")); | ||
71 | + } | ||
72 | + | ||
73 | + /** | ||
63 | * Tests the equals, hashCode and toString methods using Guava EqualsTester. | 74 | * Tests the equals, hashCode and toString methods using Guava EqualsTester. |
64 | */ | 75 | */ |
65 | @Test | 76 | @Test | ... | ... |
-
Please register or login to post a comment