2017-08-01 104 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