有两个非常相似的方法,我试图在Scala中从中提取更高阶的函数。
单向:
def delete(userId: String) = {
val entries = dao.getEntriesForIds(dao.getXXX(userId))
dao.deleteRef(entries, userId)
}
另一种方式:
def delete(userId: String) = {
val entries = dao.getEntriesForIds(dao.getXXX(userId))
.filter(_.actorId != userId)
dao.deleteRef(entries, userId)
}
我的重构版本,它似乎不是一个更高阶的函数:
def delete(userId: String, **filter: Boolean**) = {
val entries = dao.getEntriesForIds(dao.getXXX(userId))
**if (filter)**
entries.filter(_.actorId != userId)
dao.deleteRef(entries, userId)
}
如何使其成为更高阶的功能?
答案 0 :(得分:2)
E.g。
def delete(userId: String, predicate: Entry => Boolean) = {
val entries = dao.getEntriesForIds(dao.getXXX(userId)).filter(predicate)
dao.deleteRef(entries, userId)
}
// use 1
delete(userId, _ => true)
// use 2
delete(userId, _.actorId != userId)