Skip to content

Commit

Permalink
Destructuring refinements. (#26)
Browse files Browse the repository at this point in the history
Addresses remaining feedback of PR #20.
  • Loading branch information
artem-zinnatullin authored Jun 13, 2018
1 parent 8b25627 commit 4acaa4d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 25 deletions.
21 changes: 14 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ when (optional) {
}
```

#### Destructure `Optional<T>`

Koptional supports [destructuring](https://kotlinlang.org/docs/reference/multi-declarations.html).

Destructuring has same effect as calling `toNullable()`.

```kotlin
val o: Optional<T> = something.toOptional()

// If Optional is None — you'll get null, otherwise you'll get not null T value.
val (value) = o
```

#### Filter only `Some` values emitted by RxJava 2 or Project Reactor

```kotlin
Expand All @@ -80,12 +93,6 @@ val noneSignals: Observable<Unit> = Observable
Use the static `Optional.toOptional()` method (declared as a companion object method) to wrap an
instance of `T` into `Optional<T>`.

#### Destructure `Some<T>` into T

```kotlin
val (value) = Some("a")
```

### Download

Koptional is [available on jcenter](https://jcenter.bintray.com/com/gojuno/koptional).
Expand All @@ -109,7 +116,7 @@ All the releases and changelogs can be found on [Releases Page](https://github.c
Dependencies: you only need `docker` and `bash` installed on your machine.

```console
bash ci/build.sh
ci/build.sh
```

## License
Expand Down
28 changes: 10 additions & 18 deletions koptional/src/test/kotlin/com/gojuno/koptional/OptionalSpec.kt
Original file line number Diff line number Diff line change
Expand Up @@ -101,40 +101,32 @@ class OptionalSpec : Spek({
}
}

describe("component1") {
describe("destructuring") {

context("Optional<Int>.component1") {
context("destructure Optional") {

val (result) = 42.toOptional()
val (result: Int?) = 42.toOptional()

it("destructures it to Int value") {
it("destructures to its value") {
assertThat(result).isEqualTo(42)
}
}

context("None.component1") {
context("destructure None") {

val (result) = (null as Int?).toOptional()
val (result: Int?) = (null as Int?).toOptional()

it("destructures it to null") {
it("destructures to null") {
assertThat(result).isNull()
}
}

context("Lambda destructuring") {
it("destructures to Int value") {
listOf(Some(42)).forEach { (value) ->
assertThat(value).isEqualTo(42)
}
}
}

context("destructure Some") {

val some = Some("string")
val (result: String) = Some("string")

it("destructures to non-null type") {
val (value: String) = some
it("destructures to its value") {
assertThat(result).isEqualTo("string")
}
}
}
Expand Down

0 comments on commit 4acaa4d

Please sign in to comment.