Michael Strasser
06/01/2023, 11:29 AMcontext(Raise<NoSuchElementException>)
fun onlyArg(args: Array<String>): String = args.first()
How do I call this function and handle the exception? (Does this approach make sense?)Michael Strasser
06/01/2023, 11:34 AMeffect
but am not sure how to use it:
fun main(args: Array<String>) {
val arg = effect {
onlyArg(args)
}.fold(/* what here? */, /* what here? */)
}
Or is this the wrong approach?simon.vergauwen
06/01/2023, 11:52 AMsimon.vergauwen
06/01/2023, 11:54 AMensureNotNull
.
context(Raise<String>)
fun onlyArg(args: Array<String>): String =
ensureNotNull(args.firstOrNull()) { “Expected single argument, but found none” }
simon.vergauwen
06/01/2023, 11:55 AMfold
takes 2, or 3 lambdas.
The handler for String
or your error type, an optional handler for uncaught exceptions, and finally a handler for your result of the program.simon.vergauwen
06/01/2023, 11:56 AMrecover
if you simple want to recover from an error (String
).Youssef Shoaib [MOD]
06/01/2023, 5:44 PMinline fun <reified T: Throwable> Raise<T>.catchAndRaise(block: () -> A): A = catch<T>(block) { raise(it) }
Although I can imagine that Raise<Throwable>
would be quite a rare sight, but it can help the transition of code from throw to raisesimon.vergauwen
06/01/2023, 6:57 PMrunCatching { }.bind()
for that, and take into account fatal / cancellation exceptionsYoussef Shoaib [MOD]
06/01/2023, 7:01 PMResult
doesn't have a typed Throwable, and so the bind here wouldn't really work for something like Raise<NoSuchElementException>
as in the original use-case. I guess catch<NoSuchElementException>({ args.first() }) { raise(it) }
is good enough, but it might make the transition harderStylianos Gakis
06/01/2023, 11:23 PMrunCatching
also swallow cancellation exceptions? Or does arrow provide some other runCatching that I am not aware of?simon.vergauwen
06/02/2023, 5:56 AMbind
by only putting non-fatal exceptions in Raise
Michael Strasser
06/02/2023, 11:29 AMNoSuchElementException
but I am still not clear on the best way to call a function like this:
context(Raise<String>)
fun onlyArg(args: Array<String>): String =
ensureNotNull(args.firstOrNull()) { "Expected single argument, but found none" }
What is the best way to call it?Youssef Shoaib [MOD]
06/02/2023, 11:38 AMfold({ /* program goes here */ }, { /* handle success */ }, { /* handle failure */ })
Or
recover({ /* program */ }) { /* handle error */ }
Youssef Shoaib [MOD]
06/02/2023, 11:38 AMeither
and effect
Michael Strasser
06/02/2023, 11:58 AM