Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin have a Result type like Swift

Tags:

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?

like image 529
Zonily Jame Avatar asked Jul 05 '19 09:07

Zonily Jame


People also ask

What is Result in Kotlin?

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.

Is Swift like Kotlin?

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.

What is Result type in Swift?

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.


1 Answers

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)     } } 
like image 67
Smashing Avatar answered Sep 29 '22 18:09

Smashing