Search code examples
scalafor-comprehension

Understanding for-comprehension


I have the following traits:

trait Command
trait Status
trait Tr{
    def getOpt(id: Long): Option[Status]
}

and the following maps:

private val chains: mutable.Map[Long, Tr] = mutable.HashMap()
private val commandsId: mutable.Map[Command, Long] = mutable.HashMap()
private val commands: mutable.Map[Long, Command] = mutable.HashMap()

I want to implement method:

def getStatus(cmd: Command) = commandsId.get(cmd).flatMap(chains.get).flatMap{tr => 
    tr.status(id) //fail, Id was lost at commandsId.get(cmd) step
}

Is there a compact form of writing this? I suppose for-comprehension would help, but I'm not sure...


Solution

  •    commandsId.get(cmd)
         .flatMap { id =>
            chains.get(id).map(_.status(id))
         }
    

    Or, with for comprehension:

      for {
         id <- commandsId.get(cmd)
         tr <- chains.get(id)
         status <- tr.status(id)
      } yield status