St.Antario
St.Antario

Reputation: 27385

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...

Upvotes: 0

Views: 197

Answers (1)

Dima
Dima

Reputation: 40500

   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

Upvotes: 2

Related Questions