Swift has a Result
type that is declared like this
enum Result<Success, Failure: Error> { case success(Success) case failure(Failure) }
Which can be used like this:
enum FooError: Error { case fizzReason case barReason case bazReason } func returnResult() -> Result<String, FooError> { // ... Just imagine this method returns an error } switch returnResult() { case .success(let string): print(s) case .failure(.fizzReason): // do something case .failure(.barReason): // do something case .failure(.bazReason): // do something }
Does Kotlin have a similar Data Type which can be used in the same manner?
The Result class is designed to capture generic failures of Kotlin functions for their latter processing and should be used in general-purpose API like futures, etc, that deal with invocation of Kotlin code blocks and must be able to represent both a successful and a failed result of execution.
Swift is also a general-purpose programming language, just like Kotlin, which means that although it is mainly used for mobile development, it can also be used for other programming projects, like building web applications and web services.
Swift provides a special type called Result that allows us to encapsulate either a successful value or some kind of error type, all in a single piece of data. So, in the same way that an optional might hold a string or might hold nothing at all, for example, Result might hold a string or might hold an error.
I don't know whether Kotlin has something like that but here is an implementation that should do the same:
sealed class Result<out Success, out Failure> data class Success<out Success>(val value: Success) : Result<Success, Nothing>() data class Failure<out Failure>(val reason: Failure) : Result<Nothing, Failure>()
Actual example:
fun echoString(string : String) : Result<String, Exception> { return if (string.isEmpty()) { Failure(Exception("Error")) } else { Success(string) } } fun main(args : Array<String>) { when(val result = echoString("string")) { is Success -> println(result.value) is Failure -> println(result.reason) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With