Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active August 30, 2023 09:25
Show Gist options
  • Save loicdescotte/962ad3bf63728584c73ddb146a528745 to your computer and use it in GitHub Desktop.
Save loicdescotte/962ad3bf63728584c73ddb146a528745 to your computer and use it in GitHub Desktop.
Kittinunf Result usage example
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