有一个更好的方法吗?

时间:2011-02-19 18:44:48

标签: scala-2.8

所以我有这段xml代码

<schedule>
  <teacher name="Charles Xavier">
    <activities>
      <activity init="7:00" end="7:50" alias="1st period">
        <days>
          <monday></monday>
          <tuesday>room 102</tuesday>
          <wednesday></wednesday>
          <thursday></thursday>
          <friday>room 101</friday>
        </days>
      </activity>
      <activity init="8:00" end="8:50" alias="2nd period">
        <days>
          <monday></monday>
          <tuesday></tuesday>
          <wednesday>room 101</wednesday>
          <thursday></thursday>
          <friday>room 103</friday>
        </days>
      </activity>
    </activities>
  </teacher>
  <teacher name="Moira McTaggert">
    <activities>
      <activity init="7:00" end="7:50" alias="1st period">
        <days>
          <monday></monday>
          <tuesday>room 102</tuesday>
          <wednesday>room 102</wednesday>
          <thursday>room 104</thursday>
          <friday>room 101</friday>
        </days>
      </activity>
      <activity init="8:00" end="8:50" alias="2nd period">
        <days>
          <monday>room 102</monday>
          <tuesday>room 102</tuesday>
          <wednesday>room 103</wednesday>
          <thursday>room 104</thursday>
          <friday>room 103</friday>
        </days>
      </activity>
    </activities>
  </teacher>
</schedule>
到目前为止

和scala代码是

object WeekDay extends Enumeration("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") {
  type WeekDay = Value
  val Monday, Tuesday, Wednesday, Thursday, Friday = Value
}

class Teacher {
  var name: String = _
  var activities: ListBuffer[Activity] = _
}

class Activity {
  var init: String = _
  var end: String = _
  var alias: String = _
  var days: List[Day] = List(new Day(WeekDay.Monday), new Day(WeekDay.Tuesday), new Day(WeekDay.Wednesday),
    new Day(WeekDay.Thursday), new Day(WeekDay.Friday))
}

class Day(val day: WeekDay) {
  var room: String = _     
}

我认为这种方式感觉非常“势在必行”可以是更多的scala代码吗?

最终我想要完成的是一种方法(见下文),所以任何关于解决这个问题的最佳方法的提示都会受到赞赏。

var overlappedRooms = teachers.getOverlappedRooms("7:00", WeekDay.Tuesday)

这应该给我们一些信息,说Charles xavier的房间102与Moira的房间102重叠

请注意。这只是一个学习目的项目。 :)

1 个答案:

答案 0 :(得分:0)

许多Scala支持者试图避免使用可变对象,尽管有些人过分恕我直言。你可以试试这种事:

class Teacher(val name:String)

class Activity(
  val init:String,
  val end:String,
  val alias:String,
  val days:List[Day])

type Roster: Map[Teacher, List[Activity]]

请注意我已经将教师的名单移出教师,因为它不是教师的财产。你可以考虑一个新类。可能需要将活动与其所处的日期分开考虑。我不确定为什么你的Day课程有“空间”。我怀疑你的对象建模需要一些帮助。