任何人都知道如何在以下函数中减少模式匹配语句中的重复?特别是我想概括if语句。我想如果我能以某种方式将对象属性传递给函数然后我可以做到,但我不知道如何。任何帮助深表感谢。谢谢!
Ex: if (ASC) _.uid.asc else _.uid.desc
以下是功能
/**
* Finds all the users and sorts by column ascending or descending. Ascending or Descending is determined by
* if the orderBy value is positive or negative. These values are held in constants in @package models.AdminPage
* @param orderBy The column to be sorted.
* @return a list of sorted users.
*/
def findAll(orderBy: Int = DefaultSortByUid) = DB.withSession {
implicit s: Session =>
val q = for(u <- User) yield u
// Get the absolute value to determine the column to be sorted. A valid value will be an Int that corresponds
// to one of the constants defined in @package models.AdminPage.
val sortByColumn = orderBy.abs
val ASC = orderBy > 0
val users = q.sortBy(sortByColumn match {
case `SortByUid` => if (ASC) _.uid.asc else _.uid.desc
case `SortByUserName` => if(ASC) _.userId.asc else _.userId.desc
case `SortByAuthMethod` => if(ASC) _.authMethod.asc else _.authMethod.desc
case `SortByRole` => if(ASC) _.role.asc else _.role.desc
case `SortByEmail` => if(ASC) _.email.asc else _.email.desc
case `SortByFirstName` => if(ASC) _.firstName.asc else _.firstName.desc
case `SortByLastName` => if(ASC) _.lastName.asc else _.lastName.desc
//An invalid value just goes to table main page and to default sort of ascending by uid
case _ => _.uid.asc
}).list
users
}
答案 0 :(得分:1)
列对象是否共享.desc和.asc可用的公共父对象 如果是这样,你可以创建一个辅助函数:
def orderBy(direction, column) {
if (direction) column.asc else column.desc
}
并在每种情况下调用它:
case ... => orderBy(ASC, _.uid)
甚至更好地反转它并使de match返回_.uid并将其用作orderBy的输入
答案 1 :(得分:1)
这是我能做的最好的事情。谁能做得更好?
/**
* Find all users and sort by column, ascending or descending.
*
* @param orderBy Column to be sorted.
* @return Sorted list of users.
*/
def findAll(orderBy: Int = DefaultSortByUid) = DB.withSession {
implicit s: Session =>
val q = for(u <- User) yield u
// Ascending or Descending is determined by the sign of orderBy.
def sort[T] (column: Column[T]) = if (orderBy > 0) column.asc else column.desc
// Case values are defined as constants in @class models.AdminPage
q.sortBy(c => sort( orderBy.abs match {
case `SortByUserName` => c.userId
case `SortByAuthMethod` => c.authMethod
case `SortByRole` => c.role
case `SortByEmail` => c.email
case `SortByFirstName` => c.firstName
case `SortByLastName` => c.lastName
case _ => c.uid
})).list
}
答案 2 :(得分:1)
我想这可能就是你要找的东西:
/** Find all users and sort by column, ascending or descending.
*
* @param column Column to be sorted.
* @param asc Sort ascending.
* @return Sorted list of users.
*/
def findAll[T <% Ordered](column: User => T = _.uid, asc: Boolean = true) = DB withSession {
def sort(r: Records) = if (asc) column(r).asc else column(r).desc
val q = for(u <- User) yield u
q.sortBy(sort).list
}
您可以这样使用它:
val usersByEmailDesc = findAll(_.email, asc = false)
请告诉我这是否适合您 - 下一步是让生成器对此进行概括,以便将它添加到每个新表中。