Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: usere4d07
Added: Nov 6, 2019 8:46 PM
Views: 7
Tags: kotlin
  1. sealed class Result<out Success, out Failure>
  2.  
  3. data class Success<out Success>(val value: Success) : Result<Success, Nothing>()
  4. data class Failure<out Failure>(val reason: Failure) : Result<Nothing, Failure>()
  5.  
  6. // Example
  7.  
  8. fun echoString(string : String) : Result<String, Exception> {
  9.     return if (string.isEmpty()) {
  10.         Failure(Exception("Error"))
  11.     } else {
  12.         Success(string)
  13.     }
  14. }
  15.  
  16. fun main(args : Array<String>) {
  17.     when(val result = echoString("string")) {
  18.         is Success -> println(result.value)
  19.         is Failure -> println(result.reason)
  20.     }
  21. }