gpt4 book ai didi

案例类上的 Scala Type Erasure 如何解决

转载 作者:行者123 更新时间:2023-12-01 10:15:26 24 4
gpt4 key购买 nike

我有一个特征和两个扩展它的案例类:

trait Authenticatable {
val email: String
val pass: String
val id: Long
val sessionid: String
}

case class Admin(
id: Long,
email: String,
pass: String,
sessionid: Option[String] = None) extends Authenticatable

case class Client(
id: Long,
email: String,
pass: String,
sessionid: Option[String] = None) extends Authenticatable

我有一些功能,女巫应该对用户进行身份验证,使用新的 sessionid 复制对象并将其返回。

  def auth(email: String, password: String): Try[Admin] ={
checkPass(models.Admin.findBy(sqls"email = $email"), password)
}

def auth(email: String, password: String, customer: Customer): Try[Customer] ={
checkPass(models.Customer.findBy(sqls"email = $email"), password)
}

private def checkPass (model: Option[Authenticatable], password: String): Try[Authenticatable]={
model match {
case Some(m) => check(password, m.pass).map(_ => m)
case _ => Failure(new Exception("Authentication failure!"))
}
}

问题是:我无法在 auth 函数中复制对象,因为函数 checkPass 返回 Authenticatable 而不是 Client 或 Admin 类,并且 Authenticatable 没有案例类的复制方法。

解决这个问题的正确方法是什么?

最佳答案

如果您使用类型参数,您可以避免丢弃 checkPass 将始终返回相同类型的 Authenticable 的信息:

private def checkPass[A <: Authenticatable](model: Option[A], password: String): Try[A] =
// exactly the same body here

这意味着在 auth 中你可以有例如:

def auth(email: String, password: String): Try[Admin] =
checkPass(models.Admin.findBy(sqls"email = $email"), password)
.map(_.copy(sessionid = Some("whatever")))

关于案例类上的 Scala Type Erasure 如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470626/

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