使用条件编写scala函数的更好方法

使用条件编写scala函数的更好方法,scala,apache-spark,Scala,Apache Spark,我有这个函数,我在spark中用作自定义项 def convertRecipeTimeToMinutes: String => Int = (time: String) => { val size = time.size val res = if (size == 2) 0 else { var recipeTime = 0 val builder = n

我有这个函数,我在spark中用作自定义项

def convertRecipeTimeToMinutes: String => Int =
    (time: String) => {
      val size = time.size
      val res =
        if (size == 2)
          0
        else {
          var recipeTime = 0
          val builder    = new StringBuilder
          val slice      = time.slice(2, size)
          for (i <- slice) {
            if (i.isDigit) {
              builder.append(i)
            } else {
              if (i == 'H')
                recipeTime += builder.toInt * 60
              else if (i == 'M')
                recipeTime += builder.toInt

              builder.clear
            }
          }
          recipeTime
        }
      res
    }
样本输出数据


它做了必要的工作,但我想知道和学习有没有更好的方法来写这个?模式匹配,部分函数还是什么

可以使用正则表达式从字符串中提取小时和分钟:

def convertRecipeTimeToMinutes: String => Int = { time =>
  val Time = """\D*(?:(\d+)H)?(?:(\d+)M)?""".r 
  time match {
    case Time(hours, minutes) => 
      Option(hours).fold(0)(_.toInt * 60) + Option(minutes).fold(0)(_.toInt)
  }
}

查看此正则表达式的工作原理。

您可以使用正则表达式从字符串中提取小时和分钟:

def convertRecipeTimeToMinutes: String => Int = { time =>
  val Time = """\D*(?:(\d+)H)?(?:(\d+)M)?""".r 
  time match {
    case Time(hours, minutes) => 
      Option(hours).fold(0)(_.toInt * 60) + Option(minutes).fold(0)(_.toInt)
  }
}
查看此正则表达式的工作原理

def convertRecipeTimeToMinutes: String => Int = { time =>
  val Time = """\D*(?:(\d+)H)?(?:(\d+)M)?""".r 
  time match {
    case Time(hours, minutes) => 
      Option(hours).fold(0)(_.toInt * 60) + Option(minutes).fold(0)(_.toInt)
  }
}