kotlin - 如何使用高阶函数而不是简单的 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
}
解决方案
您可以使用find
foundProduct = productList.find{ it.barcode.split(',').contains(barcode) }
我也认为不需要拆分,在这种情况下
foundProduct = productList.find{ it.barcode.contains(barcode) }
推荐阅读
- powerbi - 表格视觉不直观地聚合了我的数据
- powerbi - 如何将现有的开发、测试和生产工作区分配给 Power BI 部署管道?
- javascript - Formik handleSubmit 什么都不做
- docker - 为什么 /var/run/docker.sock 的所有者和组在主机和容器之间有所不同?
- ruby-on-rails - 为什么使用 Webp-ffi gem 上传文件时出错?
- flutter - Flutter:在 List 内嵌套 Map 的条件
- javascript - 如何在我的节点应用程序中正确使用链填充方法?
- elixir - 根据一个 PubSub 事件更新所有 Phoenix LiveView 套接字
- c++ - 编译 CUDA cuSolver 特征值示例时出现编译错误
- android - 覆盖中带有 wrap_content 的 TextView 未扩展到完整内容宽度