体会下kotlin的map,filter, reduce函数的妙处
object FreqFunsTest { val TAG = "FreqFunsTest" //filter fun testFilter() { //filter就相当于if //map是集合,可以对集合中的数据作各种操作 //分别求0,1,2,3,4,5,6的阶乘,并输出奇数数组 val value = (0..6).map(::factorial).filter {it%2==1} Log.d(TAG, "testFilter: $value") //输出结果,不加filter是 // FreqFunsTest: testFilter: [1, 1, 2, 6, 24, 120, 720] 加了filter //FreqFunsTest: testFilter: [1, 1] // kotlin鼓励大家使用filter和forEach来替代常用的for循环和if条件判断 /*for (item in data.item) { if(item.useStatus == ORDERSTATUS_WAIT_TO_PAY_ZERO && item.checkExpire == true && item.status == true){ mList.add(item) } }*/ // 等同于 /*data.item .filter { it.useStatus == ORDERSTATUS_WAIT_TO_PAY_ZERO && it.checkExpire == true && it.status == true } .forEach { mList.add(it) }*/ } fun testReduce() { //reduce函数:累加函数,第一个参数是用来叠加的返回值,第二个参数是本次循环中列表的值 val index: Array<Int> = arrayOf(5, 3, 4, 9, 1, 2, 6, 8, 7, 10, 3, 11, 5, 12) val totalSum = index.reduce { acc, i -> acc + i } val totalProduct = index.reduce { acc, i -> acc * i} } }