简体   繁体   中英

FlatMap in scala

I want to write my own class ErrorOr , in which there will be cases Some and Failure . I need to write my own flatMap() , but an error pops up on the second line. How do I fix it?

object adt:
  
  enum ErrorOr[+V]:

    /* 
      Two case: 
       a case for a regular value
       a case for an error (it should contain an actual throwable)
     */
    
    case Some(x: V) extends ErrorOr[V]

    case Failure extends ErrorOr[Throwable]
    
    /* 
      in case of failing the method with exception
      no exception is thrown but the case for an error is returned
    */ 

    def flatMap[Q](f: V ⇒ ErrorOr[Q]): ErrorOr[Q] =
      this match
        case ErrorOr.Some(v)  ⇒ f(v)
        case ErrorOr.Failure  ⇒ ErrorOr[Q].Failure

I think there is something wrong with your enum. I think you are trying to do something similar to the Try[T] . You can look at the top declaration of the Try and its child classes Success Failure .

In the idea of Try.Failure, you can rewrite your ErrorOr.Failure as:

    case Failure(e : Throwable) extends ErrorOr[V]

Do not forget to change your flatMap(f) as Failure takes an argument

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM