前言
开个新坑,以后会慢慢更新
参考 Kotlin inline, noinline and crossinline
内联函数实践例子
根据传入集合里的时间戳字段,查找一天中最大的时间戳item,并且收集成集合返回
public inline fun <T> Iterable<T>.findTheDailyMaxTimestamp(crossinline predicate: (T) -> Long): List<T> { var currentDayTime = 0L val timestampArray = this.toMutableList() timestampArray.sortByDescending { predicate(it) } val returnList = mutableListOf<T>() for (item in timestampArray) { //这里是关键,从实体类中去得参数里指引的目标的字段 val time = predicate(item) if (currentDayTime == 0L) { currentDayTime = time returnList.add(item) continue } val currentCalendar = Calendar.getInstance() currentCalendar.timeInMillis = currentDayTime val crtYear = currentCalendar.get(Calendar.YEAR) val crtDay = currentCalendar.get(Calendar.DAY_OF_YEAR) val itemCalendar = Calendar.getInstance() itemCalendar.timeInMillis = time val itemYear = itemCalendar.get(Calendar.YEAR) val itemDay = itemCalendar.get(Calendar.DAY_OF_YEAR) if (crtYear == itemYear && crtDay == itemDay) { continue } currentDayTime = time returnList.add(item) } return returnList }
使用了 扩展函数 加 内联函数, 在一些需要查找一天里需要显示日期的数据集合使用,特别适合在下面图片中情景下使用(稍微改造还能变成按月查找)
使用:
val findList: List<FamilyBean> = mList.findTheDailyMaxTimestamp { it1 -> it1.createTime }
End