我是Scala的新手,请你好好的。如果我遗漏了一些明显的东西,你不得不原谅我。
我正在尝试创建一个类似枚举的结构来表示Scala中一周的日子。
我想要一个方法,接受一个字符串,可以是数字1到7,当天的全名,或三个字母的缩写,任何大小写,并返回正确的一天。理想情况下,我希望能够通过编写DayOfWeek(_)
来检索正确的日期,据我所知,事情意味着此方法需要apply
。单个值也必须是一个名为CalendarField
的特征的子类(或混合),目前这个特征不定义任何方法或成员。
这是我目前的尝试:
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
}
}
这在几点上失败了:
CalendarField
的子类 - 它们只是Value
s。apply
方法,但DayOfWeek(_)
不起作用 - 我(模糊)猜测这是因为它希望调用一个构造函数而DayOfWeek
是一个对象,而不是一类?或者是因为Enumeration(s:String)已被使用?有没有办法解决这个问题?有关如何解决这些问题或更简洁的解决方案的任何建议将不胜感激。感谢。
答案 0 :(得分:6)
我可能会实现这样的事情:
sealed trait DayOfWeek
case object Monday extends DayOfWeek
case object Tuesday extends DayOfWeek
// etc.
object DayOfWeek {
def unapply(s: String): Option[DayOfWeek] = s.toUpperCase match {
case Int(x) => x match {
case 1 => Some(Sunday)
// ...
case _ => None
}
case "SUN" | "SUNDAY" => Some(Sunday)
// ...
case _ => None
}
def apply(s: String): DayOfWeek = s match {
case DayOfWeek(d) => d
case _ => throw new IllegalArgumentException(
"Invalid value for day of week: " + s)
}
}
答案 1 :(得分:0)
使用case对象可以解决问题1,因为case对象可以有一个公共基类。由于该基类不从Enumeration
继承,因此您不会遇到继承的apply方法的问题。以下是一些示例代码:
sealed abstract class DayOfWeek {
def apply(s:String) = {
//...
}
}
case object Monday extends DayOfWeek
case object Tuesday extends DayOfWeek
//and so on...
答案 2 :(得分:0)
object WeekEnumerator{
sealed trait Week
object WeekDay extends Week
object WeekEnd extends Week
val sat, sun = WeekEnd
val mon, tue, wed, thr, fri = WeekDay
def isWorkingDay(day:WeekEnumerator.Week):Boolean = day match{
case day @ WeekEnd => false
case day @ WeekDay => true
}
}
用法:WeekEnumerator.isWorkingDay(WeekEnumerator.sun)