오류를 위한 Either
Left와 Right를 알아봅니다
오류를 위한 Either은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Either?
Either represents a value that can be one of two possibilities. It is the idiomatic way to model computations that may fail with information about the failure.
Leftconventionally holds the error.Rightconventionally holds the success value.
Unlike Option, which only tells you something is missing, Either tells you what went wrong.
The Either Type
Either[A, B] is a sealed trait with two subtypes: Left[A] and Right[B].
The mnemonic: Right is right (correct), Left is the error. This convention lets map and flatMap operate on the success side automatically.
val ok: Either[String, Int] = Right(42)
val err: Either[String, Int] = Left("boom")
println(ok)
println(err)Returning Either from a Function
A function that can fail returns an Either instead of throwing. The caller can then handle both outcomes explicitly.
object Main {
def parseAge(s: String): Either[String, Int] =
s.toIntOption match {
case Some(n) if n >= 0 => Right(n)
case Some(_) => Left("age cannot be negative")
case None => Left("not a number")
}
def main(args: Array[String]): Unit = {
println(parseAge("30"))
println(parseAge("-5"))
println(parseAge("x"))
}
}Pattern Matching on Either
The most direct way to consume an Either is pattern matching. You handle Left and Right separately.
@main def run(): Unit = {
val result: Either[String, Int] = Right(10)
val msg = result match {
case Right(value) => s"Got value: $value"
case Left(error) => s"Failed: $error"
}
println(msg)
}fold: Collapse Both Sides
fold takes two functions: one for Left and one for Right, and produces a single result of a common type.
It is a concise alternative to pattern matching when you want a value back.
@main def run(): Unit = {
val r: Either[String, Int] = Right(7)
val label = r.fold(
err => s"error: $err",
num => s"double is ${num * 2}"
)
println(label)
}map Works on the Right
map transforms the Right value and leaves a Left untouched. This is the right-biased behavior of Scala's Either (since 2.12).
@main def run(): Unit = {
val ok: Either[String, Int] = Right(5)
val no: Either[String, Int] = Left("missing")
println(ok.map(_ + 1))
println(no.map(_ + 1))
}getOrElse and Defaults
getOrElse extracts the Right value or returns a fallback when the Either is a Left.
@main def run(): Unit = {
val ok: Either[String, Int] = Right(99)
val no: Either[String, Int] = Left("oops")
println(ok.getOrElse(0))
println(no.getOrElse(0))
}swap: Flip the Sides
swap exchanges Left and Right. This is handy when you want to operate on the error side using right-biased methods.
@main def run(): Unit = {
val err: Either[String, Int] = Left("bad input")
val swapped = err.swap.map(_.toUpperCase)
println(swapped)
}isLeft and isRight
Quick boolean checks let you branch without full pattern matching.
isRightreturns true for a success.isLeftreturns true for an error.
@main def run(): Unit = {
val r: Either[String, Int] = Right(1)
println(r.isRight)
println(r.isLeft)
}toOption: Discard the Error
When you no longer care why something failed, toOption converts an Either into an Option: Right(x) becomes Some(x) and Left(_) becomes None.
@main def run(): Unit = {
val ok: Either[String, Int] = Right(3)
val no: Either[String, Int] = Left("err")
println(ok.toOption)
println(no.toOption)
}A Validation Example
Putting it together: validate a username, returning a typed error on failure.
object Main {
def validate(name: String): Either[String, String] =
if (name.isEmpty) Left("empty name")
else if (name.length > 10) Left("name too long")
else Right(name)
def main(args: Array[String]): Unit = {
println(validate("alice"))
println(validate(""))
println(validate("verylongusername"))
}
}Quick Check
Test your understanding of Either conventions.
Recap
You learned to model errors with Either:
Right= success,Left= error (right-biased).- Consume with pattern matching or
fold. - Transform the success with
map; provide defaults withgetOrElse. - Flip sides with
swap; convert withtoOption.
Next, you will handle exceptions with Try.
자주 묻는 질문
“오류를 위한 Either” 강의는 무료인가요?
네 — “오류를 위한 Either” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“오류를 위한 Either”에서 뭘 배우나요?
Left와 Right를 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“오류를 위한 Either” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 오류를 위한 Either
- Try, Success, Failure
- Either 조합
- 타입 간 변환