Skip to content

Instantly share code, notes, and snippets.

@hyunjun
Created December 12, 2020 16:40
Scala Either
@ object types {
sealed trait MyError
object MyError {
final case class LessThanZero(n: Int) extends MyError
case object Zero extends MyError
}
}
defined object types
@ import types._
import types._
@ def foo(n: Int): Either[MyError, Int] =
if (n < 0) {
Left(MyError.LessThanZero(n))
} else if (n == 0) {
Left(MyError.Zero)
} else {
Right(n * 100)
}
defined function foo
@ foo(10)
res3: Either[MyError, Int] = Right(1000)
@ foo(0)
res4: Either[MyError, Int] = Left(Zero)
@ foo(-10)
res5: Either[MyError, Int] = Left(LessThanZero(-10))
@ foo(-10) match {
case Right(n) => println(s"Right result: $n")
case Left(MyError.LessThanZero(n)) => println(s"n should not be less than zero n: $n")
case Left(MyError.Zero) => println(s"n should not be zero")
}
n should not be less than zero n: -10
// 값을 받아서 사용하는 쪽에서 빠진 부분이 있으면 compile time에 오류를 발견할 수 있음. 물론 이걸 커버하려면 test code에서 잘 찾아야 함
// test case에 foo(0)가 없으면 이런 오류를 미리 찾을 수는 없을테니
@ foo(0) match {
case Right(n) => println(s"Right result: $n")
case Left(MyError.LessThanZero(n)) => println(s"n should not be less than zero n: $n")
}
scala.MatchError: Left(Zero) (of class scala.util.Left)
ammonite.$sess.cmd12$.<clinit>(cmd12.sc:1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment