這是不是一個廣泛的問題。如何避免在我的情況下編寫類似結構的代碼?
我使用Akka +噴霧劑進行小型項目。然而,我注意到,我一直在寫有類似的結構,他們都承擔相似之處,爲實例代碼,一些塊看起來是這樣:
val response = (secCompanyActor ? WebGetOneCompany)
.mapTo[TransOk]
.map(result => result.succeedOrNot match {
case true => (OK, result.company.get)
case false => (BadRequest, result.errorMessage)
})
complete(response)
其他塊看起來是這樣的:(唯一的區別是TransAllOk
而不是TransOK
)
val response = (secCompanyActor ? CasperGetAllCompanies)
.mapTo[TransAllOk].map(result => result.succeedOrNot match {
case true => (OK, result.companies.get)
case false => (BadRequest, result.errorMessage)
}).recover { case _ => (BadRequest, "An error has occurred! We will fix this")}
complete(response)
的TransOK
和TransAllOK
簽名是在這裏:
case class TransOk(company: Option[Company.Company], errorMessage: Option[String])
case class TransAllOk(companies: Option[List[Company.Company]], errorMessage: Option[String])
索姆etimes,有一些簡單的GET->返回數據庫在我的計劃,看起來非常相似的查詢:
case Register =>
val result = DAL.db.withSession{ implicit session =>
MTurker.insert()
}
sender ! TransOk(result._1, result._2, result._3)
和下一個調用不同的對象不同的方法,但結構是一樣的:
case WebGetOneCompany =>
val result = DAL.db.withSession{ implicit session =>
Company.getOneCompany()
}
sender ! TransOk(result._1, result._2, result._3)
Company
和MTurker
是一個對象。
什麼類型的知識可以幫助我編寫更簡潔的代碼來處理我目前的問題?泛型?
給'TransOk'和'TransAllOk'一個共同的父母,然後是在父定義函數和'TransOk'和'TransAllOk'返回'result.compa實現它ny.get'或'result.companies.get'。這將允許您編寫一個函數,將他的消息發送到'secCompanyActor',並可以進行必要的處理。 – wingedsubmariner
@wingedsubmariner這是斯卡拉模式嗎?它有名字嗎? –
它是亞型多態性。這是每種OO語言的模式。 – wingedsubmariner