Hatalar için Either
Left ve Right
Hatalar için Either, CoddyKit'te ücretsiz bir Scala for Backend Engineering & Functional Programming dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Scala for Backend Engineering & Functional Programming öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Scala for Backend Engineering & Functional Programming kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“Hatalar için Either” dersi ücretsiz mi?
Evet — “Hatalar için Either” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Scala for Backend Engineering & Functional Programming kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Scala for Backend Engineering & Functional Programming kursu toplamda 4 dersten oluşur.
“Hatalar için Either” dersinde ne öğreneceğim?
Left ve Right Scala for Backend Engineering & Functional Programming ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Scala for Backend Engineering & Functional Programming öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Scala for Backend Engineering & Functional Programming, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.
“Hatalar için Either” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Scala for Backend Engineering & Functional Programming dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Scala for Backend Engineering & Functional Programming dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Hatalar için Either
- Try, Success, Failure
- Either Birleştirme
- Türler Arasında Dönüştürme