← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 6 of 7

Either Type क्या है

एक Either दो संभावित जवाबों में से एक रखता है, आमतौर पर बाईं ओर एक बुरा या दाईं ओर एक अच्छा। यह एक दरवाज़े जैसा है जो prize या explanation में से किसी एक की ओर खुलता है।

In this page:

  1. The Either Type
Syntax
scala
def function_name(param: Type): Either[ErrorType, ResultType] =
  if (condition) Right(value) else Left(error)

result match {
  case Left(error) => expression
  case Right(value) => expression
}

The Either Type

Either[L, R] दो संभावित outcomes में से एक को represent करता है: एक Left(value) (convention के अनुसार एक error) या एक Right(value) (convention के अनुसार एक success)। Try के विपरीत, जो specifically exceptions के लिए है, Either आपको error case के लिए कोई भी type उपयोग करने देता है, जैसे कोई descriptive error message या custom error type।

Pattern matching, या modern .map/.flatMap methods (जो convention के अनुसार Right side पर operate करते हैं), इसके साथ काम करने के standard तरीके हैं।

Note: Convention के अनुसार, Right success को represent करता है और Left failure को -- एक उपयोगी याद रखने का तरीका है कि Right का मतलब "सही" भी है।

उदाहरण: The Either Type

markup
object Main extends App {
  def divide(a: Int, b: Int): Either[String, Int] = {
    if (b == 0) Left("Cannot divide by zero")
    else Right(a / b)
  }

  val result1 = divide(10, 2)
  val result2 = divide(10, 0)

  println(result1)
  println(result2)

  result2 match {
    case Right(value) => println(s"Result: $value")
    case Left(error) => println(s"Error: $error")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि Left success value है, जबकि convention के अनुसार Right सही value है और Left error है।
  2. Either[String, Int] जैसे types भूल जाना, जिससे compiler Either[String, Nothing] infer करता है।
  3. किसी Either पर .get call करना, जबकि इसमें कोई get नहीं है और आपको match, map या fold का उपयोग करना चाहिए।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.