- Parsing a Url
- Fetching from the Url
- the URL may not be well formed, and
- fetching from a remote url may have network issues
So onto the basics of how such a call can be made using the Result type. You can imagine that parsing URL can return this Result type, capturing any exception that may result from such a call:
1 2 | fun parseUrl(url: String): Result<URL> = kotlin.runCatching { URL(url) } |
1 2 3 | urlResult.isSuccess == true urlResult.isFailure == false |
1 2 3 | urlResult.getOrNull() // Returns null if the block completed with an exception urlResult.getOrDefault(URL( "http://somedefault" )) // Returns a default if the block completed with an exception urlResult.getOrThrow() // Throws an exception if the block completed with an exception |
1 2 | val hostResult: Result<String> = urlResult.map { url -> url.host } |
1 | val getResult: Result<String> = urlResult.mapCatching { url -> throw RuntimeException( "something failed!" ) } |
1 2 3 4 5 6 | fun parseUrl(url: String): Result<URL> = kotlin.runCatching { URL(url) } fun getFromARemoteUrl(url: URL): Result<String> { return kotlin.runCatching { "a result" } } |
1 2 | val getResult: Result<String> = urlResult.flatMap { url -> getFromARemoteUrl(url)} |
I can do today is a bit of hack:
OR even better, create an extension function which makes flatMap available to "Result" type, this way and use it:
This concludes my exploration of the Result type and the ways to use it. I have found it to be a excellent type to have in my toolbelt.
1 2 | val getResult: Result<String> = urlResult.mapCatching { url -> getFromARemoteUrl(url).getOrThrow() } |
1 2 3 4 5 6 7 | fun <T, R> Result<T>.flatMap(block: (T) -> (Result<R>)): Result<R> { return this .mapCatching { block(it).getOrThrow() } } val getResult: Result<String> = urlResult.flatMap { url -> getFromARemoteUrl(url)} |