如何将枚举类型传递给函数

时间:2020-07-23 17:31:52

标签: scala

我有一个枚举

object UserTokenType extends Enumeration {
  type TokenType = Value
  val RegistrationConfirmation = Value("RegistrationConfirmation")
  val ResetPasswordConfirmation = Value("ResetPasswordConfirmation")
}

我想将其传递给这样的函数

def generateEmailTokenForUser(user:User,tokenType:UserTokenType) = {..}

但以上内容无法编译。

我需要将它作为Int传递吗?我关心的是如何检查是否已传递有效的枚举值?

2 个答案:

答案 0 :(得分:2)

如评论中所建议,您可以使用Value,它是Enumeration中定义的类(请参阅链接的文档)。您不能在此处直接使用UserToken,因为它不是类或类型(因此这样称呼它会产生误导)。

工作代码示例:

object UserToken extends Enumeration {
  val RegistrationConfirmation = Value("RegistrationConfirmation")
  val ResetPasswordConfirmation = Value("ResetPasswordConfirmation")
}


val v:UserToken.Value = UserToken.ResetPasswordConfirmation

def generateEmailTokenForUser(user:User, token:UserToken.Value) = {
  token match {
    case UserToken.RegistrationConfirmation => println("case 1")
    case UserToken.ResetPasswordConfirmation => println("case 2")
  }
}

答案 1 :(得分:1)

如果您想保留原始方法签名,请尝试以下操作

object UserTokenType extends Enumeration {
  type UserTokenType = Value
  val RegistrationConfirmation = Value("RegistrationConfirmation")
  val ResetPasswordConfirmation = Value("ResetPasswordConfirmation")
}
import UserTokenType._

def generateEmailTokenForUser(tokenType: UserTokenType) = ???
generateEmailTokenForUser(RegistrationConfirmation)

我们将类型别名更改为

type UserTokenType = Value

,然后将其带入范围

import UserTokenType._

或者考虑使用enumeratum

import enumeratum._

sealed trait UserTokenType extends EnumEntry

object UserTokenType extends Enum[UserTokenType] {
  val values = findValues
  case object RegistrationConfirmation extends UserTokenType
  case object ResetPasswordConfirmation extends UserTokenType
}
import UserTokenType._

def generateEmailTokenForUser(tokenType: UserTokenType) = tokenType
generateEmailTokenForUser(RegistrationConfirmation)

请注意,将单例对象和单例对象的类型之间的差异视为值

val x:         Int        =      42
val y: UserTokenType.type = UserTokenType
                |                 |
               type             value

所以当你写

def generateEmailTokenForUser(tokenType: UserTokenType)

在原理上类似于

def f(x: 42)