Either Type क्या है
In this page:
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 तरीके हैं।
उदाहरण: The Either Type
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")
}
}
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि
Leftsuccess value है, जबकि convention के अनुसारRightसही value है औरLefterror है। Either[String, Int]जैसे types भूल जाना, जिससे compilerEither[String, Nothing]infer करता है।- किसी
Eitherपर.getcall करना, जबकि इसमें कोईgetनहीं है और आपकोmatch,mapयाfoldका उपयोग करना चाहिए।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: