Created
March 31, 2018 22:38
-
-
Save sorokod/1d45d03d8e25700873edf8c1e4ca8b8c to your computer and use it in GitHub Desktop.
Result and OptionalResult sealed classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package result | |
import result.Result.Err | |
import result.Result.Ok | |
sealed class Result<out T> { | |
data class Ok<out T>(val value: T) : Result<T>() | |
data class Err(val exception: Exception = RuntimeException(), val msg: String = "") : Result<Nothing>() | |
} | |
sealed class OptionalResult<out T> { | |
object None : OptionalResult<Nothing>() | |
data class Some<out T>(val value: T) : OptionalResult<T>() | |
} | |
fun main(args: Array<String>) { | |
fun query(id: Int): Result<String> = when (id) { | |
1 -> Ok("a result") | |
else -> Err(msg = "something went wrong...") | |
} | |
val result1 = query(1) | |
val result2 = query(2) | |
val result = result2 | |
when (result) { | |
is Ok -> println("Got ${result.value}") | |
is Err -> { | |
val (exe, msg) = result | |
println("Exception = $exe , msg = $msg") | |
} | |
} | |
} | |
// ############################################################################## | |
package optionalresult | |
import optionalresult.OptionalResult.* | |
sealed class OptionalResult<out T> { | |
object None : OptionalResult<Nothing>() | |
data class Some<out T>(val value: T) : OptionalResult<T>() | |
data class Err(val exception: Exception = RuntimeException(), val msg: String = "") : OptionalResult<Nothing>() | |
fun expect(errorMsg: String): T = when (this) { | |
is None -> throw IllegalStateException(errorMsg) | |
is Err -> throw IllegalStateException(errorMsg) | |
is Some -> this.value | |
} | |
} | |
fun main(args: Array<String>) { | |
fun query(id: Int): OptionalResult<String> = when (id) { | |
0 -> None | |
1 -> Some("a result") | |
else -> Err(msg = "something went wrong...") | |
} | |
val result = query(0) | |
when (result) { | |
is None -> println("not found") | |
is Some -> println("Got ${result.value}") | |
is Err -> { | |
val (exe, msg) = result | |
println("Exception = $exe , msg = $msg") | |
} | |
} | |
lateinit var r : OptionalResult<String> | |
lateinit var v: String | |
// v = None.expect("expected: a result") // IllegalStateException: expected a result | |
// v = Err().expect("expected: a result") // IllegalStateException: expected a result | |
v = Some("a result").expect("expected: a result") // v has the value "a result" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment