scala:如何以功能方式处理Option

Cha*_*dra 2 scala

我是scala的新手,所以我的问题可能完全是愚蠢的.如果我有一个像下面这样的现有方法.我将这4行添加到方法中.有没有更好的方法来处理期权价值?

def processData(input: String, dataMap: Map[String, String]): Option[String] = {

   //4 lines I am adding.
   val data: Option[String] = dataMap.get(input)
   if (data.isEmpty) {
     return None
   }

   //how to avoid this line
   val dataValue = data.get

   //20-25 lines of code in here with bunch of pattern matching case statements
   cleanData(dataValue)
   doSomethingElse("apple", dataValue, "test")
}
Run Code Online (Sandbox Code Playgroud)

基本上我想避免在下面的代码中执行"data.get".这称之为感觉不对.我可以使用模式匹配以不同的方式编写这个.但是20-25行代码有大量的case语句,我不想​​在它们之上创建另一个层.

def processData(input: String, dataMap: Map[String, String]): Option[String] = {

 dataMap.get(input) match {

   case Some(dataValue) => {
   //20-25 lines of code in here with bunch of pattern matching case statements
    cleanData(dataValue)
    doSomethingElse("apple", dataValue, "test")
  }
   case None => None
 }
Run Code Online (Sandbox Code Playgroud)

}

有任何想法吗?

ka4*_*eli 6

实际上你的第二种方式是功能风格,但为了简洁起见,你可以使用其中一个Option更高阶的功能:

  def processData(input: String, dataMap: Map[String, String]): Option[String] = 
    dataMap.get(input).map { dataValue =>
      cleanData(dataValue)
      doSomethingElse("apple", dataValue, "test")
    }
Run Code Online (Sandbox Code Playgroud)

你甚至可以避免使用圆点和圆括号:

  def processData(input: String, dataMap: Map[String, String]): Option[String] = 
    dataMap get input map { dataValue =>
      cleanData(dataValue)
      doSomethingElse("apple", dataValue, "test")
    }
Run Code Online (Sandbox Code Playgroud)