Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing String and Enumeration

Tags:

scala

I have an enumeration in scala mapped to strings in JPA. For more comfortable coding, I defined implicit conversions between them. So I now can define value val person.role = "User", - person.role is the enumeration type "User" a String so there's the conversion. But when I try to compare these two, I always get false, because the def equals (arg0: Any) : Boolean takes Any so there's not any conversion triggered. I need some explicit conversion, but my plan was to be able to omit that, what do you think is the best practice | neatest solution here?

like image 853
ryskajakub Avatar asked Aug 04 '10 15:08

ryskajakub


1 Answers

Expanding on Thomas's answer, if you're using the comparison to branch, using pattern matching may be more appropriate:

object Role extends Enumeration {
   val User = MyValue("User")
   val Admin = MyValue("Admin")

   def MyValue(name: String): Value with Matching = 
         new Val(nextId, name) with Matching

   // enables matching against all Role.Values
   def unapply(s: String): Option[Value] = 
      values.find(s == _.toString)

   trait Matching {
      // enables matching against a particular Role.Value
      def unapply(s: String): Boolean = 
            (s == toString)
   }
}

You can then use this as follows:

def allowAccess(role: String): Boolean = role match {
   case Role.Admin() => true
   case Role.User() => false
   case _ => throw ...
}

or

// str is a String
str match { 
   case Role(role) => // role is a Role.Value
   case Realm(realm) => // realm is a Realm.Value
   ...
}
like image 105
Aaron Novstrup Avatar answered Oct 04 '22 20:10

Aaron Novstrup