Either 조합
map과 flatMap을 알아봅니다
Either 조합은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Composing Computations
Real programs chain several fallible steps: parse, validate, look up, compute. Either lets you compose these so that the first failure short-circuits the whole chain.
The tools are map, flatMap, and for-comprehensions.
flatMap Sequences Eithers
flatMap applies a function that itself returns an Either. If the receiver is Left, the function is never called and the Left propagates.
object Main {
def positive(n: Int): Either[String, Int] =
if (n > 0) Right(n) else Left("not positive")
def main(args: Array[String]): Unit = {
val r = Right(5).flatMap(positive)
val l = Right(-1).flatMap(positive)
println(r)
println(l)
}
}Short-Circuiting
When you chain multiple flatMap calls, the first Left stops everything. Later steps are skipped, and that error becomes the final result.
object Main {
def step(label: String, n: Int): Either[String, Int] = {
println(s"running $label")
Right(n + 1)
}
def main(args: Array[String]): Unit = {
val result = Left("early error").asInstanceOf[Either[String, Int]]
.flatMap(n => step("A", n))
.flatMap(n => step("B", n))
println(result)
}
}for-Comprehension over Either
Because Either is right-biased, you can use it in a for-comprehension. Each <- unwraps a Right; any Left stops the comprehension and becomes the result.
object Main {
def parse(s: String): Either[String, Int] =
s.toIntOption.toRight(s"bad: $s")
def main(args: Array[String]): Unit = {
val sum = for {
a <- parse("3")
b <- parse("4")
} yield a + b
println(sum)
}
}A Failing for-Comprehension
If any step in the comprehension yields a Left, the whole expression is that Left and subsequent steps do not run.
object Main {
def parse(s: String): Either[String, Int] =
s.toIntOption.toRight(s"bad: $s")
def main(args: Array[String]): Unit = {
val sum = for {
a <- parse("3")
b <- parse("oops")
c <- parse("5")
} yield a + b + c
println(sum)
}
}Chaining Validations
A realistic pipeline: parse a string, then check a business rule, then transform. Each stage returns an Either.
object Main {
def parse(s: String): Either[String, Int] = s.toIntOption.toRight("not a number")
def checkRange(n: Int): Either[String, Int] =
if (n >= 1 && n <= 100) Right(n) else Left("out of range")
def process(s: String): Either[String, Int] =
parse(s).flatMap(checkRange).map(_ * 10)
def main(args: Array[String]): Unit = {
println(process("7"))
println(process("500"))
println(process("x"))
}
}map vs flatMap
Use map when your function returns a plain value. Use flatMap when it returns another Either, to avoid a nested Either[String, Either[String, Int]].
@main def run(): Unit = {
val withMap: Either[String, Int] = Right(2).map(_ + 1)
val nested: Either[String, Either[String, Int]] = Right(2).map(n => Right(n + 1))
val flat: Either[String, Int] = Right(2).flatMap(n => Right(n + 1))
println(withMap)
println(nested)
println(flat)
}Combining Independent Values
A for-comprehension also works when each step does not depend on the previous one. All must succeed for the final yield to run.
object Main {
def parse(s: String): Either[String, Int] = s.toIntOption.toRight(s"bad: $s")
def main(args: Array[String]): Unit = {
val combined = for {
x <- parse("10")
y <- parse("20")
z <- parse("30")
} yield List(x, y, z).sum
println(combined)
}
}leftMap-Style Error Transformation
Standard library Either has no leftMap, but you can transform the error with swap.map(...).swap or by mapping inside a fold. This keeps error types consistent across a pipeline.
@main def run(): Unit = {
val e: Either[String, Int] = Left("low-level error")
val mapped = e.swap.map(msg => s"context: $msg").swap
println(mapped)
}Putting It All Together
A small calculator pipeline that parses two numbers and divides, reporting any failure as a typed error.
object Main {
def parse(s: String): Either[String, Int] = s.toIntOption.toRight(s"bad number: $s")
def divide(a: Int, b: Int): Either[String, Int] =
if (b == 0) Left("division by zero") else Right(a / b)
def calc(x: String, y: String): Either[String, Int] =
for {
a <- parse(x)
b <- parse(y)
r <- divide(a, b)
} yield r
def main(args: Array[String]): Unit = {
println(calc("20", "4"))
println(calc("20", "0"))
println(calc("x", "4"))
}
}Why This Matters
Composing Either gives you railway-oriented programming: the happy path flows through Right, and any error diverts onto the Left track and bypasses the rest. No exceptions, no null checks, just values.
Quick Check
Test your understanding of composing Either.
Recap
You learned to compose Either:
flatMapsequences fallible steps and short-circuits on the firstLeft.for-comprehensions read cleanly for multi-step pipelines.- Use
mapfor plain results,flatMapfor Either-returning functions. - Transform errors with
swap.map(...).swap.
자주 묻는 질문
“Either 조합” 강의는 무료인가요?
네 — “Either 조합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“Either 조합”에서 뭘 배우나요?
map과 flatMap을 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“Either 조합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.