gpt4 book ai didi

Scala - 避免过于复杂的嵌套模式匹配

转载 作者:行者123 更新时间:2023-12-02 06:06:18 24 4
gpt4 key购买 nike

我尝试简化在 Spray 中为 HTTP 请求提供响应的验证过程(我使用 Slick 进行数据库访问)。目前,我检查一个查询是否应该进一步执行以下查询(返回错误)。这最终导致嵌套模式匹配。每个验证案例都会返回不同的错误,因此我不能使用任何 flatMap。

class LocationDao {
val db = DbProvider.db

// Database tables
val devices = Devices.devices
val locations = Locations.locations
val programs = Programs.programs
val accessTokens = AccessTokens.accessTokens

def loginDevice(deviceSerialNumber: String, login: String, password: String): Either[Error, LocationResponse] = {
try {
db withSession { implicit session =>
val deviceRowOption = devices.filter(d => d.serialNumber === deviceSerialNumber).map(d => (d.id, d.currentLocationId.?, d.serialNumber.?)).firstOption
deviceRowOption match {
case Some(deviceRow) => {
val locationRowOption = locations.filter(l => l.id === deviceRow._2.getOrElse(0L) && l.login === login && l.password === password).firstOption
locationRowOption match {
case Some(locationRow) => {
val programRowOption = programs.filter(p => p.id === locationRow.programId).firstOption
programRowOption match {
case Some(programRow) => {
val program = Program(programRow.name, programRow.logo, programRow.moneyLevel, programRow.pointsForLevel,
programRow.description, programRow.rules, programRow.dailyCustomerScansLimit)
val locationData = LocationData(program)
val locationResponse = LocationResponse("access_token", System.currentTimeMillis(), locationData)
Right(locationResponse)
}
case None => Left(ProgramNotExistError)
}
}
case None => Left(IncorrectLoginOrPasswordError)
}
}
case None => Left(DeviceNotExistError)
}
}
} catch {
case ex: SQLException =>
Left(DatabaseError)
}
}
}

有什么好方法可以简化这个过程?也许还有其他方法..

最佳答案

通常,您可以使用 for 理解将此处的许多单子(monad)结构链接在一起(包括 TryOptionEither) 没有嵌套。例如:

for {
val1 <- Try("123".toInt)
} yield for {
val2 <- Some(val1).map(_ * 2)
val3 = Some(val2 - 55)
val4 <- val3
} yield val4 * 2

按照您的风格,这可能看起来像:

Try("123".toInt) match {
case Success(val1) => {
val val2 = Some(val1).map(_ * 2)
val2 match {
case Some(val2value) => {
val val3 = Some(val2value - 55)
val3 match {
case Some(val4) => Some(val4)
case None => None
}
}
case None => None
}
case f:Failure => None
}
}

关于Scala - 避免过于复杂的嵌套模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28718836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com