Reputation: 222
I want to write a method like this:
def validate[T <: Enumeration](input: String)(implicit enum: T) : Seq[T]
that will take an input ("foo,bar,baz") and split it with commas - then compare to the enumerations given. For example, given this enum:
object Letter extends Enumeration {
type Letter = Value
val first = Value("A")
val second = Value("B")
val third = Value("C")
}
the expected output of validate[Letter]("A,B,C,D")
would be: Seq[Letter](first,second,third)
.
I've tried doing something like this:
val inputValues = input.split(",").toSeq
for {
inputValue <- inputValues
enumValue <- enum.values
if enumValue.toString == inputValue
} yield enumValue
But it doesn't compile, because of the type system... is there another way to implement this?
Upvotes: 2
Views: 353
Reputation: 12563
Cannot do it with implicit enum, but with explicit enum something like that seems to be possible:
scala> import scala.util.Try
scala> def validate[T <: Enumeration](input: String, enum: T):Seq[T#Value] = {
| val inputValues = input.split(",").toSeq
| for (value <- inputValues if Try(enum.withName(value)).isSuccess) yield enum.withName(value) }
validate: [T <: Enumeration](input: String, enum: T)Seq[T#Value]
scala> validate("A,B,D", Letter)
res12: Seq[Letter.Value] = ArrayBuffer(A, B)
Upvotes: 3