- 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:
fun parseUrl(url: String): Result<URL> = kotlin.runCatching { URL(url) }
val urlResult: Result<URL> = parseUrl("http://someurl") urlResult.isSuccess == true urlResult.isFailure == false
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
val urlResult: Result<URL> = parseUrl("http://someurl") val hostResult: Result<String> = urlResult.map { url -> url.host }
val getResult: Result<String> = urlResult.mapCatching { url -> throw RuntimeException("something failed!") }
fun parseUrl(url: String): Result<URL> = kotlin.runCatching { URL(url) } fun getFromARemoteUrl(url: URL): Result<String> { return kotlin.runCatching { "a result" } }
val urlResult: Result<URL> = parseUrl("http://someurl") val getResult: Result<String> = urlResult.flatMap { url -> getFromARemoteUrl(url)}
I can do today is a bit of hack:
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.
val urlResult: Result<URL> = parseUrl("http://someurl") val getResult: Result<String> = urlResult.mapCatching { url -> getFromARemoteUrl(url).getOrThrow() }OR even better, create an extension function which makes flatMap available to "Result" type, this way and use it:
fun <T, R> Result<T>.flatMap(block: (T) -> (Result<R>)): Result<R> { return this.mapCatching { block(it).getOrThrow() } } val urlResult: Result<URL> = parseUrl("http://someurl") val getResult: Result<String> = urlResult.flatMap { url -> getFromARemoteUrl(url)}