我正在尝试以功能样式重写函数。我知道功能不好。但是如何避免使用 var 字段watermarkTime
?
该函数为具有连续增加时间戳的行设置第“1”天。如果时间戳小于上一行的时间戳,则设置天“2”。
case class Row(time: String, name: String, var day: Int)
val rows = List(new Row("09:18:52", "3_0711-082757_01001", 0),
new Row("09:23:18", "3_0711-082757_01002", 0),
new Row("09:33:43", "3_0711-082757_01004", 0),
new Row("10:20:00", "3_0711-082757_01011", 0),
new Row("05:03:38", "3_0711-082757_02001", 0), // set secound day
new Row("05:07:51", "3_0711-082757_02002", 0),
new Row("05:13:02", "3_0711-082757_02003", 0),
new Row("05:19:16", "3_0711-082757_02004", 0),
new Row("10:54:27", "3_0711-082757_02015", 0), // set first day
new Row("11:00:38", "3_0711-082757_02016", 0),
new Row("11:07:28", "3_0711-082757_02017", 0))
def setDayFP(rows: List[Row]): List[Row] = {
var watermarkTime = 0
for (row <- rows) {
val newTime = row.time.replaceAll(":","").toInt
if (watermarkTime < newTime) {
watermarkTime = newTime
row.day = 1
} else {
row.day = 2
}
}
return rows
}
这是结果(按日期和名称排序):
Row(09:18:52,3_0711-082757_01001,1)
Row(09:23:18,3_0711-082757_01002,1)
Row(09:33:43,3_0711-082757_01004,1)
Row(10:20:00,3_0711-082757_01011,1)
Row(10:54:27,3_0711-082757_02015,1)
Row(11:00:38,3_0711-082757_02016,1)
Row(11:07:28,3_0711-082757_02017,1)
Row(05:03:38,3_0711-082757_02001,2)
Row(05:07:51,3_0711-082757_02002,2)
Row(05:13:02,3_0711-082757_02003,2)
Row(05:19:16,3_0711-082757_02004,2)
我正在寻找更好的解决方案。提前致谢!
庞戈