首页 > 解决方案 > 如何使用高阶函数而不是简单的 for 将这个 Kotlin 代码翻译成更好的代码

问题描述

我有这个接收条形码并在具有相同条形码的列表中查找产品的功能。这split( ",")是因为有些产品的条码不止一个,这样写​​的:("barcode1,barcode2")

有人可以帮助我使用高阶函数而不是这个 for 循环来获得更好的代码吗?

fun Product.byBarcode(barcode: String?) : Product? {
    val productsList = Realm.getDefaultInstance().where(Product::class.java).findAll().toMutableList()
    var foundProduct : Product? = null
    for (it in productsList){
        if ( it.barcode.split(",").contains(barcode)){
            foundProduct = it
            break
        }
    }
    return foundProduct

}

标签: kotlin

解决方案


您可以使用find

foundProduct = productList.find{ it.barcode.split(',').contains(barcode) }

我也认为不需要拆分,在这种情况下

foundProduct = productList.find{ it.barcode.contains(barcode) }

推荐阅读