案例类方法的高阶函数



我正在尝试删除代码中的冗余。我想我可以用高阶函数来做。

我想做的是把公共比特分解到f3中,然后让f1和f2之间不同的比特成为传递到f3的参数。

object Example extends App {
case class action(name: String, age: Int) {
def setName(new_name: String): action = this.copy(name = new_name)
def setAge(new_age: Int): action = this.copy(age = new_age)
}
def f1(x: action, increment: Int) = {
// big block of code which does a....
// a single line in the block calling
val older_person = x setAge (x.age + increment)
// big block of code which does b....
}
def f2(x: action, new_name: String) = {
// big block of code which does a....
// a single line in the block calling
val new_name_person = x setName new_name
// big block of code which does b....
}
/* Now as there is clearly a redundancy, which can be solved by higher order functions.
I want to combine f1 and f2 into a single function. The function will take in the action, the value, and the 
function to apply. It will then call the relevant function inside the method.
*/
def f3[T](x: action)(f: T => action)(value: T) = {
// big block of code which does a....
// call x.f(value)
val new_action = ??? 
// big block of code which does b....
}
// then in my code I can call like this:
// f3(x)(setAge)(100)
// f3(x)(setName("new_name")
}

我困惑的是,如何在case类中传递一个方法函数?有没有一种优雅的方式来做这件事?

f3中,您可以简单地接受类型为Action => Action的函数(我将使用Action而不是action来减少混淆(。

def f3(x: Action)(copy: Action => Action) = {
// big block of code which does a....
// a single line in the block calling
val new_name_person = copy(x)
// big block of code which does b....
}

然后你可以定义一些有用的函数,并使用currying使它们更容易在以后使用:

object Action {
def setName(name: String)(action: Action) = action.copy(name=name)
def incAge(inc: Int)(action: Action) = action.copy(age=action.age+inc)
}

然后像这样使用:

val x = Action("Foo", 42)
f3(x)(Action.incAge(100))
f3(x)(Action.setName("new_name"))

在Scastie 中试用

最新更新