Last active
August 30, 2023 09:25
-
-
Save loicdescotte/962ad3bf63728584c73ddb146a528745 to your computer and use it in GitHub Desktop.
Kittinunf Result usage example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.github.kittinunf.result.* | |
open class AppError(message: String) : Throwable(message) | |
class ReadError(message: String) : AppError("Read error " + message) | |
class WriteError(message: String) : AppError("Write error " + message) | |
fun main(args: Array<String>) { | |
val result: Result<Unit, AppError> = readArgs(args).flatMap { writeToConsole(it) } | |
result.onSuccess { println("Success") } | |
result.onFailure { error -> println("App Error " + error.message) } | |
} | |
private fun readArgs(args: Array<String>) = Result.of<Int, ReadError> { | |
try { | |
args.get(0).toInt() + args.get(1).toInt() | |
} catch (e: Exception) { | |
throw ReadError(e.message?:"") | |
} | |
} | |
private fun writeToConsole(it: Int) = Result.of<Unit, WriteError> { | |
try { | |
println("result : " + it) | |
} catch (e: Exception) { | |
throw WriteError(e.message?:"") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment