理解理解

时间:2017-08-01 16:49:00

标签: scala for-comprehension

我有以下特点:

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

以及以下地图:

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()

我想实现方法:

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

是否有紧凑的写作形式?我认为理解会有所帮助,但我不确定......

1 个答案:

答案 0 :(得分:2)

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

或者,for理解:

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