在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):michaelbull/kotlin-result开源软件地址(OpenSource Url):https://github.com/michaelbull/kotlin-result开源编程语言(OpenSource Language):Kotlin 100.0%开源软件介绍(OpenSource Introduction):kotlin-result
Installationrepositories {
mavenCentral()
}
dependencies {
implementation("com.michael-bull.kotlin-result:kotlin-result:1.1.16")
} IntroductionThe Mappings are available on the wiki to assist those with experience
using the Read MoreBelow is a collection of videos & articles authored on the subject of this library. Feel free to open a pull request on GitHub if you would like to include yours.
Getting StartedThe idiomatic approach to modelling operations that may fail in Railway
Oriented Programming is to avoid throwing an exception and instead make the
return type of your function a fun checkPrivileges(user: User, command: Command): Result<Command, CommandError> {
return if (user.rank >= command.mininimumRank) {
Ok(command)
} else {
Err(CommandError.InsufficientRank(command.name))
}
} To incorporate the val result: Result<Customer, Throwable> = runCatching {
customerDb.findById(id = 50) // could throw SQLException or similar
} Nullable types, such as the val result: Result<Customer, String> = customers
.find { it.id == id } // returns Customer?
.toResultOr { "No customer found" } Transforming ResultsBoth success and failure results can be transformed within a stage of the
railway track. The example below demonstrates how to transform an internal
program error ( val result: Result<Treasure, UnlockResponse> =
unlockVault("my-password") // returns Result<Treasure, UnlockError>
.mapError { IncorrectPassword } // transform UnlockError into IncorrectPassword ChainingResults can be chained to produce a "happy path" of execution. For example, the
happy path for a user entering commands into an administrative console would
consist of: the command being tokenized, the command being registered, the user
having sufficient privileges, and the command executing the associated action.
The example below uses the tokenize(command.toLowerCase())
.andThen(::findCommand)
.andThen { cmd -> checkPrivileges(loggedInUser, cmd) }
.andThen { execute(user = loggedInUser, command = cmd, timestamp = LocalDateTime.now()) }
.mapBoth(
{ output -> printToConsole("returned: $output") },
{ error -> printToConsole("failed to execute, reason: ${error.reason}") }
) Binding (Monad Comprehension)The In the example below, should fun functionX(): Result<Int, DomainError> { ... }
fun functionY(): Result<Int, DomainError> { ... }
fun functionZ(): Result<Int, DomainError> { ... }
val sum: Result<Int, DomainError> = binding {
val x = functionX().bind()
val y = functionY().bind()
val z = functionZ().bind()
x + y + z
}
println("The sum is $sum") // prints "The sum is Ok(100)" The Coroutine SupportUse of suspending functions within a dependencies {
implementation("com.michael-bull.kotlin-result:kotlin-result:1.1.16")
implementation("com.michael-bull.kotlin-result:kotlin-result-coroutines:1.1.16")
} The coroutine implementation of The example below demonstrates a computationally expensive function that takes five milliseconds to compute being eagerly cancelled as soon as a smaller function fails in just one millisecond: suspend fun failsIn5ms(): Result<Int, DomainErrorA> { ... }
suspend fun failsIn1ms(): Result<Int, DomainErrorB> { ... }
runBlocking {
val result = binding<Int, BindingError> {
val x = async { failsIn5ms().bind() }
val y = async { failsIn1ms().bind() }
x.await() + y.await()
}
// result will be Err(DomainErrorB)
} InspirationInspiration for this library has been drawn from other languages in which the Result monad is present, including: It also iterates on other Result libraries written in Kotlin, namely: Improvements on the existing solutions include:
ExampleThe example module contains an implementation of Scott's
example application that demonstrates the usage of It hosts a ktor server on port 9000 with a PayloadsFetch customer information
Add new customer
ContributingBug reports and pull requests are welcome on GitHub. LicenseThis project is available under the terms of the ISC license. See the
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论