Scala 获取给定月份最近 12 个月的列表

Scala Get List of last 12 months from given month

请注意 scala 初学者问题。 我正在尝试获取所选月份过去 12 个月的列表。但是下面的代码给出了错误: Unit 类型的表达式不符合预期类型 List[String]

不确定哪个部分需要修复。任何帮助将不胜感激。谢谢

 def getlistofmonths(currentmonth: String): List[String] = {
    //val currentmonth="202006"

    val monthDate = new SimpleDateFormat("yyyyMM")
    val cal: Calendar = Calendar.getInstance

    cal.setTime(monthDate.parse(currentmonth))

    for (x <- 1 until 12) {
      monthDate.format(cal.getTime).toList
      cal.add(Calendar.MONTH, -1)
    }

  }

注意:正如 Krzysztof Atłasik 建议的那样,只有在 Java 7 或更旧版本之前才使用此解决方案。我的解决方案解释了为什么您需要新的日历实例,因为它是可变的。

import java.text.SimpleDateFormat
import java.util.{Calendar}

val currentmonth = "202006"

def getlistofmonths(currentmonth: String): List[String] = {
  //val currentmonth="202006"

  (1 to 12)
    .map(e => {
      val monthDate = new SimpleDateFormat("yyyyMM")
      val cal: Calendar = Calendar.getInstance
      cal.setTime(monthDate.parse(currentmonth))
      cal.add(Calendar.MONTH, -e)
      monthDate.format(cal.getTime)
    })
    .toList

}
getlistofmonths(currentmonth)

由于同一个对象在您的代码中发生了变化,您不能使用同一个日历实例。因此,作为上述代码的一部分,它将创建一个日历实例并返回必要的过去 12 个月。

Expression of type Unit doesn't conform to expected type List[String]

这意味着你说你的函数 returns 是 List[String],但你实际上没有返回任何东西(因此你的函数实际上 returns Unit).

Unsure which part needs the fix.

要解决此错误,您需要将结果填充到列表中,然后 return 在函数末尾添加它。

(我不是在解决方法实现本身,因为那将是一个不同的问题;但正如@Krzysztof Atłasik 在评论中提到的那样,您应该避免再使用 java.util.Calendar...)

除非您使用的是非常旧的 Java(版本 7 或以下),否则您不应使用 Calendar。它是可变的,并且有一个更好的选择 YearMonth from java.time:

import java.time.LocalDate
import java.time.format.DateTimeFormatter

def getlistofmonths(currentmonth: String): List[String] = {

  val monthDate = DateTimeFormatter.ofPattern("yyyyMM")

  val start = YearMonth.parse(currentmonth, monthDate)

  (1 to 12).map(x => start.minusMonths(x).format(monthDate)).toList

}