如何用scala方式编写这个函数?

时间:2016-07-25 03:30:58

标签: scala

考虑到这种情况,我有一堆服务都需要检查输入并处理错误。

val log = Logger("access")

def service1(){input=> 
    try{ 
        val id = input.split(",")(0).toInt
        val value = input.split(",")(1)
        //do something
    } catch {
        case e1: NumberFormatException => log.info("number format is wrong")
        case e2: ArrayIndexOutOfBoundsException=> log.info("not enough arguments")
    }
}

我想编写一个方法来处理每个服务的这个公共部分。我可以这样做:

def common(input:String, log:Logger, action:(Int)=>String):String={
    try{ 
        val id = input.split(",")(0).toInt
        val value = input.split(",")(1)
        action(id)
    } catch {
        case e1: NumberFormatException => log.info("number format is wrong")
        case e2: ArrayIndexOutOfBoundsException=> log.info("not enough arguments")
    }
}

然后服务功能如下所示:

def service1(){input=> common(input, log, id=>{
         //do something return a string
    })
}

有没有办法跳过共同的参数,使它看起来像集合中的地图一样优雅?

common(id=>{ //... })

1 个答案:

答案 0 :(得分:1)

import com.typesafe.scalalogging.StrictLogging


class MyService extends AbstractService {
  def service1(input: String): String = common(input) {
    id =>
      id.toString
  }

  def service2(input: String): String = common(input) {
    id =>
      id.toString.toLowerCase
  }
}

trait AbstractService extends StrictLogging {

  def common(input: String)(f: Int => String): String = {
    try {
      val id = input.split(",")(0).toInt
      f(id)
    } catch {
      case e1: NumberFormatException =>
        logger.error("number format is wrong",e1)
        "" //???
      case e2: ArrayIndexOutOfBoundsException =>
        logger.error("not enough arguments",e2)
        "" //???
    }
  }
}

如果输入是特定的,您必须将其作为输入。否则,在trait中定义方法def input:String并提供服务实现。