Scala 如何从整数值创建枚举

Scala 如何从整数值创建枚举,scala,Scala,我的应用程序具有以下Enum object UserTokenType extends Enumeration { type TokenType = Value val RegistrationConfirmation = Value("RegistrationConfirmation") val ResetPasswordConfirmation = Value("ResetPasswordConfirmation") } 我使用enum的id将enum的值存储在数据库中。当我从

我的应用程序具有以下
Enum

object UserTokenType extends Enumeration {
  type TokenType = Value
  val RegistrationConfirmation = Value("RegistrationConfirmation")
  val ResetPasswordConfirmation = Value("ResetPasswordConfirmation")
}
我使用
enum
id
将enum的值存储在数据库中。当我从数据库中读取值时,我想重新创建
Enum
,以便在数据模型中传递它。目前,我已经做了如下工作

val userTokenType:UserTokenType.TokenType = if(row.getInt("is_sign_up") == UserTokenType.RegistrationConfirmation.id) {
      UserTokenType.RegistrationConfirmation
    }else{
      UserTokenType.ResetPasswordConfirmation
    }

以上是将
Int
转换为
Enum
的正确方法吗?

正如注释中提到的@som snytt,您可以使用[apply(x:Int)](:Enumeration.this.Value)构造Enum:

row.getInt("is_sign_up") match {
  case id if id >= 0 && id < UserTokenType.maxId => Some(UserTokenType(id))
  case _ => None
}
row.getInt(“是否注册”)匹配{
如果id>=0&&idSome(UserTokenType(id))
案例=>无
}

对象X扩展枚举{val A,B=Value};X(0)
。没有人再使用枚举了。谢谢。如果是,Enum的等价物是什么?我通常发现它们比使用整型文字更有用。我也是,这是它们的最佳用例。关于scala 2的建议是更喜欢java枚举或带有case对象子对象的密封特征。scala 3具有适当的枚举支持。懒惰的人可能
尝试(UTT(id))。toOption