这里有两个问题:
1)多个陈述需要{...}
括号:
从
mapped.foreach((item: (Date, Long)) => item XXX // OK YYY // NO )
至
mapped.foreach { (item: (Date, Long)) => item XXX // OK YYY // OK }
2)val
不能重新分配:
从
val last: Option[Tuple2[java.util.Date, Long]] = None
至
var last: Option[Tuple2[java.util.Date, Long]] = None
重构#1
我会尽量避免使用var
.似乎在这种情况下if (last.isDefined)
我们可能会尝试自己zip
的列表:
scala> val l = List(1, 2, 3, 4, 5) scala> l.zip(l.tail) List[(Int, Int)] = List((1,2), (2,3), (3,4), (4,5))
重构你的例子:
import java.util.Date def interpolate(l: List[(String, String)]): List[(Date, Long)] = { val mapped: List[(Date, Long)] = l.map(item => (format.parse(item._1), item._2.toLong)) val results = ListBuffer[(Date, Long)]() mapped.zip(mapped.tail).foreach { case ((lastDate, lastLong), (itemDate, itemLong)) => val daysItem = itemDate.getTime / 1000 / 60 / 60 / 24 val daysLast = lastDate.getTime / 1000 / 60 / 60 / 24 if (daysItem - daysLast > 1) { val slope = (itemLong - lastLong) / (daysItem - daysLast) val days = daysLast until daysItem val missingChunk: List[(Date, Long)] = days.map(day => (new Date(day * 24 * 60 * 60 * 1000), slope * day)).toList results ++= missingChunk } } results.toList }
重构#2
ListBuffer
是一个可变的集合.在我们的场景,似乎我们正试图flatten
在missingChunk
秒.
继续重构:
def interpolate(l: List[(String, String)]): List[(Date, Long)] = { val mapped: List[(Date, Long)] = l.map(item => (format.parse(item._1), item._2.toLong)) val missingChunks = mapped.zip(mapped.tail).map { case ((lastDate, lastLong), (itemDate, itemLong)) => val daysItem = itemDate.getTime / 1000 / 60 / 60 / 24 val daysLast = lastDate.getTime / 1000 / 60 / 60 / 24 if (daysItem - daysLast > 1) { val slope = (itemLong - lastLong) / (daysItem - daysLast) val days = daysLast until daysItem days.map(day => (new Date(day * 24 * 60 * 60 * 1000), slope * day)).toList } else List.empty[(Date, Long)] } missingChunks.flatten }