Skip to content

Commit

Permalink
Support Option.orNull() (#2572)
Browse files Browse the repository at this point in the history
  • Loading branch information
mincong-h committed Apr 25, 2020
1 parent 1063d56 commit 0b7a72c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/main/java/io/vavr/control/Option.java
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,23 @@ public final Option<T> orElse(Supplier<? extends Option<? extends T>> supplier)
return isEmpty() ? (Option<T>) supplier.get() : this;
}

/**
* Returns this {@code Option} if this is defined, or {@code null} if it is empty.
*
* <pre>{@code
* // = Some("Hello World")
* Option.of("Hello World").orNull();
*
* // = null
* Option.none().orNull();
* }</pre>
*
* @return this value if it is defined, or {@code null} if it is empty.
*/
public final T orNull() {
return isEmpty() ? null : get();
}

/**
* Returns the value if this is a {@code Some}, otherwise {@code supplier.get()} is returned.
* <p>
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/io/vavr/control/OptionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,18 @@ public void shouldReturnAlternativeOnOrElseSupplierIfValueIsNotDefined() {
assertThat(Option.none().orElse(() -> opt)).isSameAs(opt);
}

// -- orNull

@Test
public void shouldReturnValueOnOrNullIfValueIsDefined() {
assertThat(Option.of("v").orNull()).isEqualTo("v");
}

@Test
public void shouldReturnValueOnOrNullIfValueIsEmpty() {
assertThat(Option.none().orNull()).isNull();
}

// -- getOrElse

@Test
Expand Down

0 comments on commit 0b7a72c

Please sign in to comment.