当前位置:  开发笔记 > 编程语言 > 正文

Scala不是Any的成员

如何解决《Scala不是Any的成员》经验,为你挑选了1个好方法。



1> Filippo Vita..:

这里有两个问题:

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是一个可变的集合.在我们的场景,似乎我们正试图flattenmissingChunk秒.

继续重构:

  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
  }

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有