From ed430c4eca1388da70d3f9c79c5ee0a3d7c46ff9 Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Sat, 24 Aug 2019 00:31:23 +0100 Subject: [PATCH] Update "Creating Results" section in README --- README.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index de5975a..4179691 100644 --- a/README.md +++ b/README.md @@ -36,17 +36,6 @@ using the `Result` type in other languages: ### Creating Results -To begin incorporating the `Result` type into an existing codebase, you can -wrap functions that may fail (i.e. throw an `Exception`) with -[`Result.of`][result-of]. This will execute the block of code and `catch` any -`Exception`, returning a `Result`. - -```kotlin -val result: Result = Result.of { - customerDb.findById(id = 50) // could throw SQLException or similar -} -``` - The 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 `Result`. @@ -61,6 +50,17 @@ fun checkPrivileges(user: User, command: Command): Result } ``` +To incorporate the `Result` type into an existing codebase that throws +exceptions, you can wrap functions that may `throw` with +[`runCatching`][result-runCatching]. This will execute the block of code and +`catch` any `Throwable`, returning a `Result`. + +```kotlin +val result: Result = runCatching { + customerDb.findById(id = 50) // could throw SQLException or similar +} +``` + Nullable types, such as the `find` method in the example below, can be converted to a `Result` using the `toResultOr` extension function. @@ -201,9 +201,9 @@ This project is available under the terms of the ISC license. See the [`LICENSE`](LICENSE) file for the copyright information and licensing terms. [result]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Result.kt#L10 -[result-ok]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Result.kt#L30 -[result-err]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Result.kt#L35 -[result-of]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Result.kt#L17 +[result-ok]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Result.kt#L31 +[result-err]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Result.kt#L36 +[result-runCatching]: https://github.com/michaelbull/kotlin-result/blob/master/src/main/kotlin/com/github/michaelbull/result/Factory.kt#L11 [swalschin-rop]: https://fsharpforfunandprofit.com/rop/ [wiki]: https://github.com/michaelbull/kotlin-result/wiki [unit-tests]: https://github.com/michaelbull/kotlin-result/tree/master/src/test/kotlin/com/github/michaelbull/result