I'm new to Scala, so be nice please. You'll have to excuse me if I'm missing something obvious.
I'm trying to create an enum like structure to represent the days of the week in Scala.
I want a method that accepts a string that can either be the numbers 1 through 7, the full name of the day, or a three letter abbreviation, with any capitalisation, and returns the correct day. Ideally I want to be able to retrieve the correct day simply by writing DayOfWeek(_)
, which as far as I understand things means this method needs to be apply
. The individual values also have to be subclasses (or mix in) a trait called CalendarField
, which at the moment defines no methods or members.
This is my current attempt:
object DayOfWeek extends Enumeration with CalendarField {
val Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday = Value
def apply(v:String) = {
v.toUpperCase match {
case Int(x) => x match {
case 1 => Sunday
case 2 => Monday
case 3 => Tuesday
case 4 => Wednesday
case 5 => Thursday
case 6 => Friday
case 7 => Saturday
case _ => throw new IllegalArgumentException("Invalid value for day of week: " + v)
}
case "SUN" | "SUNDAY" => Sunday
case "MON" | "MONDAY" => Monday
case "TUE" | "TUEDAY" => Tuesday
case "WED" | "WEDNESDAY" => Wednesday
case "THU" | "THURSDAY" => Thursday
case "FRI" | "FRIDAY" => Friday
case "SAT" | "SATURDAY" => Saturday
case _ => throw new IllegalArgumentException("Invalid value for day of week: " + v)
}
}
}
object Int {
def unapply(s : String) : Option[Int] = try {
Some(s.toInt)
} catch {
case _ : java.lang.NumberFormatException => None
}
}
This fails on a few points:
- The individual values aren't subclasses of
CalendarField
- they are simplyValue
s. - I've defined an
apply
method butDayOfWeek(_)
doesn't work - my (vague) guess this is because it expects to call a constructor andDayOfWeek
is an object, not a class? Or is it because Enumeration(s:String) is already used? Is there a way round this?
Any suggestions on how to get round these problems, or neater solutions, would be greatly appreciated. Thanks.