简体   繁体   中英

Scala: Chain multiple functions with Try[T] as the return type

I am new to functional programming in Scala and am working on a module where each operators (class instance/object) are chained together. The operators has only one function and that returns a Try[T]. I'm looking for a more readable way of chaining them together.

trait Mapper {
    def map(in: T): Try[T]
}

trait Reducer {
    def reduce(in: T): Try[T]
}

trait Grouper {
    def group(in: T, batchSize: int): Try[T]
}

Lets just say I have created the implementations for these traits. Now in my main function, I can do something like

object MyApp extends App {
    val mapper: Mapper = ...
    val reducer: Reducer = ...
    val grouper: Grouper = ...  

    def run(): Try[Unit] = {
        val inp: T = ...
        mapper.map(inp) match {
            case Success(x) => reducer.reduce(x) match {
                case Success(y) => grouper.group(x) match {
                    case Success(z) => ..// some other function call
                    case Failure(e) => throw e
                }
                case Failure(e) => throw e
                }
           case Failure(e) => throw e
        }
    }

   run()
}

Is there a way, I can avoid all these Success, Failure pattern matching and do it in a better way?

Simple and typical for-comprehension is the case:

def run(): Try[Unit] = {
    val inp: T = ...
    for {
     mapResult <- mapper.map(inp)
     reduceresult <- reducer.reduce(mapResult)
     groupResult <- grouper.group(x)
    } yield ()
}

You can find lot's of learning materials about this topic in internet, but essentially this is syntax sugar over flatMap , map , withFilter and foreach for cases like yours.

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