使用函数作为参数转换函数

时间:2016-03-27 04:12:41

标签: scala

我有一些与以下

相同的代码伙伴的函数
def updateFoo(fooId: Long, user: String): Option[Foo] = {

  val fooMaybe = fooDao.getById(fooId)
  fooMaybe match {
    case Some(foo) =>
      fooDao.update(
        foo.copy(updatedBy = Some(user), validationStatus = Some(ValidationStatus.Valid))
      )
    case None =>
      throw new Exception(s"Foo with ID: '$fooId' doesn't exist")
  }
}

其中Foo是一个案例类。

为了减少重复的代码,我编写了以下函数,旨在由其他函数共享

  private def doIt(f1: Long => Option[Object],  parameter1: Long, f2: Object => Option[Object], paramter2: String ): Option[Object] ={

val somethingMaybe = f1(parameter1)
somethingMaybe match {
  case Some(something) =>
    f2(
      something.copy(updatedBy = Some(paramter2),
        validationStatus = Some(ValidationStatus.Valid)) // <-- can't be complied 
    )
  case None =>
    throw new DomainException(s"Object with ID: '$parameter1' doesn't exist")
 }
}

这是对的吗?

1 个答案:

答案 0 :(得分:0)

您声明f2函数只接受一个参数:

f2: Object => Option[Object]

但您使用两个参数调用此函数:

f2(
  something.copy(updatedBy = Some(paramter2),
  validationStatus = Some(ValidationStatus.Valid) // <-- can't be complied 
)

也许你想改变你的f2声明,如:

f2: (Object, Option[ValidationStatus]) => Option[Object]