精妙的理解:如何处理可以为None或Something的枚举数?

时间:2019-05-28 08:42:57

标签: scala slick

我有一个用例,可能不特定于Slick,而是用于理解。高级模式是这样的,但它会导致enum3中的编译器错误:

(for {
   enum1 <- // ...
   enum2 <- // ...
   enum3 <- optionArg.fold(empty result).map { ... }
 } yield ())

然后我结束了下面的编译,但是具有重复的代码,即enum1和enum2:

optionArg match { 
  case (Some(arg)) => {
     (for {
        enum1 <- // ...
        enum2 <- // ...
        enum3 <- // do something with arg          
      } yield ())
    }
    case None => {
     (for {
        enum1 <- // ...
        enum2 <- // ...
      } yield ())
    }
  }        
}  

具体来说,我有这个重复的变体可以编译:

/**
 * Returns the inserted `oauth2Info` instance including the params. We first
 * look up the `LoginInfo` by the relevant search criteria, fetching its `userId`
 * which is then used to persist a `OAuth2Info` and multiple `OAuth2InfoParam`.
 *
 * @param extLoginInfo The login info for which the auth info should be added.
 * @param extOAuth2Info The TOTP info to add containing the params.
 * @return the inserted `oauth2Info` instance including the params.
 */
def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val insertion = extOAuth2Info.params match {
      case Some(params) => {
        (for {
          userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
          _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
          _ <- DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
        } yield ())
      }
      case None => {
        (for {
          userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
          _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
        } yield ())
      }
    }
    db.run(insertion.transactionally).map(_ => extOAuth2Info)
}

这个简洁的变体不:

def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val insertion = (for {
      userId <- LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
      _ <- (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
      _ <- extOAuth2Info.params.fold(DBIOAction.seq()) { params =>
        DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
      }
    } yield ()).transactionally
    db.run(insertion).map(_ => extOAuth2Info)
}

给出编译错误:

[play-silhouette-seed] $ compile
[info] Formatting 1 Scala source ProjectRef(uri("file:/home/skywalker/code/play-silhouette-seed/"), "root")(compile) ...
[info] Compiling 1 Scala source to /home/skywalker/code/play-silhouette-seed/target/scala-2.12/classes ...
[error] /home/skywalker/code/play-silhouette-seed/app/models/daos/OAuth2InfoDaoImpl.scala:58:28: type mismatch;
[error]  found   : slick.dbio.DBIOAction[scala.collection.immutable.Iterable[Int],slick.dbio.NoStream,slick.dbio.Effect.Write]
[error]  required: slick.dbio.DBIOAction[Unit,slick.dbio.NoStream,slick.dbio.Effect]
[error]         DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
[error]                            ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed May 28, 2019 10:42:00 AM

1 个答案:

答案 0 :(得分:1)

当编译器无法为表达式表达式类型正确地推断类型时,这就是fold的问题。它不能正确地将第一个表达式返回的类型扩展为第二个表达式的类型。您需要一点帮助编译器。

在这种情况下也会发生

 Some(123).fold(None)(_ => Some("123"))
 // type mismatch; found: Some[String] required: None.type

您可以将fold更改为map().getOrElse()(然后“好类型”首先出现并得到推断)。

或者您可以在某处添加类型注释,例如

 private val noAction: slick.dbio.DBIOAction[Iterable[Int],NoStream,Effect.Write] 
   = DBIOAction.sequence()

 theOption.fold(noAction)(params => .... )

此外,如果您发现重复的代码,则可以通过移出通用表达式来减轻这种情况。使用Slick之类的功能性(无副作用)代码,这种重构非常安全。您只需使用需要运行的Slick操作构建几个valdef,以后再进行组合即可。

def add(extLoginInfo: ExtLoginInfo, extOAuth2Info: ExtOAuth2Info): Future[ExtOAuth2Info] = {
    val getUserId = LoginInfo.filter { loginInfo => loginInfo.providerId === extLoginInfo.providerID && loginInfo.providerKey === extLoginInfo.providerKey }.map(_.userId).result.head
    val insertOAuth = for {
        userId <- getUserId 
        _ = (OAuth2Info += OAuth2InfoRow(userId, extOAuth2Info.accessToken, extOAuth2Info.tokenType, extOAuth2Info.expiresIn, extOAuth2Info.refreshToken))
    } yield userId


    val insertion = extOAuth2Info.params match {
      case Some(params) => {
        (for {
          userId <- insertOAuth
          _ <- DBIOAction.sequence(params.map { param => (OAuth2InfoParam += OAuth2InfoParamRow(userId, param._1, param._2)) })
        } yield ())
      }
      case None => 
         insertOAuth
    }
    db.run(insertion.transactionally).map(_ => extOAuth2Info)
}