Oğuzhan Soykan
01/05/2024, 11:22 AMCLOVIS
01/05/2024, 11:26 AMTry
is essentially just an Either
that catches exceptions. In Arrow, you can use:
val foo: Either<Throwable, Int> = Either.catch {
5 % 0
}
to catch exceptions with regular Either
.
Is there anything else from Try
that you would find useful?Oğuzhan Soykan
01/05/2024, 11:44 AMEither.catch
is a feature Scala does not implement as far as I know and offloads this burden to Try
.raulraja
01/05/2024, 12:04 PMTry
in Arrow in the 0.x series but we removed it a some point in favor of Kotlin's Result which models the same thing https://blog.rockthejvm.com/functional-error-handling-in-kotlin-part-2/raulraja
01/05/2024, 12:06 PMScala Kotlin
Try(block) -> runCatching { ... }
Success(value) -> Result.success(value)
Failure(ex) -> Result.failure(e)
raulraja
01/05/2024, 12:39 PMTry
constructor is implemented only capturing NonFatal
exceptions:
https://github.com/scala/scala/blob/13a80bd6faea2d9a53f40305853debd3900e729e/src/library/scala/util/Try.scala#L220
https://github.com/scala/scala/blob/13a80bd6faea2d9a53f40305853debd3900e729e/src/library/scala/util/control/NonFatal.scala#L42
In contrast the implementation of runCatching
may capture exceptions that in most cases are considered Fatal and something you should. not recover from:
https://github.com/JetBrains/kotlin/blob/e959e97992507f4ecc84eca3fab829692ec05376/libraries/stdlib/src/kotlin/util/Result.kt#L144
In Arrow for Either.catch
and other variations of catch
we check if the exception is fatal and if it is we rethrow it.
https://github.com/arrow-kt/arrow/blob/731a9b292ab5f2f8ba2decc251dab3f2c4a60c06/ar[…]core/arrow-core/src/commonMain/kotlin/arrow/core/raise/Raise.ktraulraja
01/05/2024, 12:43 PMYes you’re right. It pretty much does the same job. Do you think that it is a design decision about not implementing Try as a separate monad?The design decision here was motivated becauseis a feature Scala does not implement as far as I know and offloads this burden toEither.catch
.Try
Try
was the same as Result
but Result lacks a way to bubble up fatal exceptions with nonFatalOrThrow
.
We decided to remove Try
, keep nonFatalOrThrow
as public APIs in case you want to use them with try/catch
and provide catch
variations as functions and constructors for Error Handling related types.Oğuzhan Soykan
01/05/2024, 2:49 PM