任何人都知道如何在以下函数中减少模式匹配语句中的重复?具体来说,我想概括 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
}