Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toNullable() specialization. #21

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions koptional/src/main/kotlin/com/gojuno/koptional/Optional.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@ package com.gojuno.koptional

sealed class Optional<out T : Any> {

fun toNullable(): T? = when (this) {
is Some -> value
is None -> null
}
/**
* Converts [Optional] to either its non-null value if it's [Some] or `null` if it's [None].
*/
abstract fun toNullable(): T?
}

data class Some<out T : Any>(val value: T) : Optional<T>() {
override fun toString() = "Some($value)"
override fun toNullable(): T = value
}

object None : Optional<Nothing>() {
override fun toString() = "None"
override fun toNullable(): Nothing? = null
}

fun <T : Any> T?.toOptional(): Optional<T> = if (this == null) None else Some(this)
23 changes: 20 additions & 3 deletions koptional/src/test/kotlin/com/gojuno/koptional/OptionalSpec.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class OptionalSpec : Spek({

context("Some.toNullable") {

val result = Some("string").toNullable()
val result: String = Some("string").toNullable()

it("converts it to value") {
assertThat(result).isEqualTo("string")
Expand All @@ -21,7 +21,25 @@ class OptionalSpec : Spek({

context("None.toNullable") {

val result = None.toNullable()
val result: Nothing? = None.toNullable()

it("converts it to null") {
assertThat(result as Any?).isNull()
}
}

context("Optional.Some.toNullable") {

val result: String? = (Some("string") as Optional<String>).toNullable()

it("converts it to value") {
assertThat(result).isEqualTo("string")
}
}

context("Optional.None.toNullable") {

val result: Nothing? = (None as Optional<Nothing>).toNullable()

it("converts it to null") {
assertThat(result as Any?).isNull()
Expand Down Expand Up @@ -80,7 +98,6 @@ class OptionalSpec : Spek({
it("converts it to String") {
assertThat(result).isEqualTo("None")
}

}
}
})