Scala で成功 / 失敗を表すなら Either 型ではなく Try 型を使おう
Either[A, B] 型は直和型。Right[A] or Left[B]
Scala Standard Library 2.13.6 - scala.util.Either
TypeScriptTypeScript.icon での Union 型っぽいもの
更に柔軟にすると Coproduct 型 (餘積)
入門⚡Shapeless#1.5. Coproduct
缺點
Left 型と Right 型が餘り非對稱でない
Left 型の型 parameter が自由過ぎる
Left[String] と Left[Exception] 等を混ぜるのは面倒
withFilter method が定義されてゐない
for 內包表記で if guard が使へない
throw する code を Either 型に變換する code が長い
code:scala
try {
Right(processMayFail())
} catch {
case e => Left(e.getMessage)
}
code:scala
// Try 型を經由する
Try { processMayFail() }.toEither.left.map(_.getMessage)
利點
成功失敗とか關係無い時に便利
Try[T] 型は Success[T] or Failure[Throwable]
Scala Standard Library 2.13.6 - scala.util.Try
Either 型で譬へると Either[Throwable, T]
Either 型と比べて
Success 型と Failure 型の意味は明白で非對稱
Failure 型の型 parameter は Throwable 型に限定される
getMessage method 等は必ず呼べる
更なる meta data を要求する code が在っても、その code に向けた變更は getMessage method 等しか要らない code へは影響しない
withFilter method も定義されてゐる
for 內包表記が制限無く使へる
throw する code を Try 型に短い code で變換できる
code:scala
Try { processMayFail() }
RustRust.icon にも Result<T, E> 型と either::Either<L, R> 型が有る
std::result - Rust
either::Either - Rust