spebbe / dartz

Functional programming in Dart
MIT License
749 stars 60 forks source link

How to use get left object from Either? #85

Closed ahuruFoundation closed 2 years ago

ahuruFoundation commented 2 years ago

Hi, Im quite new to darz. Is there a way to just get the left object of Either?

For example, Im returning Either<Failure, Type> from a method. final result = method(); if (result.isLeft()) { //doesn't seem like there is a result.getLeft }

thanks.

spebbe commented 2 years ago

Hi @ahuruFoundation !

The main purpose of Either is to make it impossible to forget to handle failures, by using fold or getOrElse, which ensures that failures are either handled or recovered. However, if you really need to, you can do this:

    if (result is Left<Failure, Type>) {
      print(result.value); // ...or whatever you want to do. Don't forget to handle Right values as well ;-)
    }

This mechanism is considered an escape hatch though and risks defeating the purpose of using Either in the first place.

Hope that helped!

ahuruFoundation commented 2 years ago

thanks, that really helps.

fullflash commented 1 year ago

there is no value in dartz package

result.value