How to extract Left or Right easily from Either type in Dart (Dartz)

Ok here the solutions of my problems: To extract/retrieve the data final Either<ServerException, TokenModel> result = await repository.getToken(…); result.fold( (exception) => DoWhatYouWantWithException, (tokenModel) => DoWhatYouWantWithModel ); //Other way to ‘extract’ the data if (result.isRight()) { final TokenModel tokenModel = result.getOrElse(null); } To test the exception //You can extract it from below, or test it directly … Read more

Getting Value of Either

Nicolas Rinaudo’s answer regarding calling getOrElse on either the left or right projection is probably the closest to Option.getOrElse. Alternatively, you can fold the either: scala> val x: Either[String,Int] = Right(5) x: Either[String,Int] = Right(5) scala> val a: String = x.fold(l => “left”, r => r.toString) a: String = 5 As l is not used … Read more

Idiomatic error handling in Clojure

Clojure error handling is generally JVM exception (unchecked) oriented. Slingshot makes using exceptions more pleasant by allowing, for example, destructuring on thrown exception values. For an alternative that allows erlang-style error handling you should look at dire. This blog post gives a good overview of the rational for dire as well as an overview of … Read more

Method parameters validation in Scala, with for comprehension and monads

If you’re willing to use Scalaz, it has a handful of tools that make this kind of task more convenient, including a new Validation class and some useful right-biased type class instances for plain old scala.Either. I’ll give an example of each here. Accumulating errors with Validation First for our Scalaz imports (note that we … Read more

Using Eithers with Scala “for” syntax

It doesn’t work in scala 2.11 and earlier because Either is not a monad. Though there’s talk of right-biasing it, you can’t use it in a for-comprehension: you have to get a LeftProject or RightProjection, like below: for { foo <- Right[String,Int](1).right bar <- Left[String,Int](“nope”).right } yield (foo + bar) That returns Left(“nope”), by the … Read more

Throwing exceptions in Scala, what is the “official rule”

The basic guideline is to use exceptions for something really exceptional**. For an “ordinary” failure, it’s far better to use Option or Either. If you are interfacing with Java where exceptions are thrown when someone sneezes the wrong way, you can use Try to keep yourself safe. Let’s take some examples. Suppose you have a … Read more

Using Either to process failures in Scala code

Either is used to return one of possible two meaningful results, unlike Option which is used to return a single meaningful result or nothing. An easy to understand example is given below (circulated on the Scala mailing list a while back): def throwableToLeft[T](block: => T): Either[java.lang.Throwable, T] = try { Right(block) } catch { case … Read more