2017-08-01 55 views
0

我有以下特点:理解为,理解

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 
} 

有一个紧凑的形式写这个?我想换的理解会有所帮助,但我不知道......

回答

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 
+0

很有意思,谢谢了。 AFAIK for-comprehension只是糖。你能解释一下它实际编译的内容吗? –

+1

@ St.Antario你可以用编译器标志'-Xprint:parser'来检查你自己 – puhlen