项目开发中涉及到一个请求实体,如果为空,就设置为"",这样grpc的服务端,就获取不多这个值,就不作为处理条件了
代码如下:
val cmdbPrice: Cmdb.Price = Cmdb.Price.newBuilder()
.setSkuId(takeIf { condition.skuId == null }?.let { "" } ?: condition.skuId)
.setFastoneStrategy(takeIf { condition.fastoneStrategy == null }?.let { "" } ?: condition.fastoneStrategy)
.setProductLevel(takeIf { condition.productLevel == null }?.let { "" } ?: condition.productLevel)
.setFastoneRegion(takeIf { condition.fastoneRegion == null }?.let { "" } ?: condition.fastoneRegion)
.setVendor(takeIf { condition.vendor == null }?.let { "" } ?: condition.vendor)
.setProductType(takeIf { condition.productType?.name == null }?.let { "" } ?: condition.productType?.name)
.setSystemPlatform(takeIf { condition.systemPlatform?.name == null }?.let { "" }
?: condition.systemPlatform?.name)
.setFastoneModel(takeIf { condition.fastoneModel == null }?.let { "" } ?: condition.fastoneModel)
.setFastoneFamily(takeIf { condition.fastoneFamily == null }?.let { "" } ?: condition.fastoneFamily)
.setVendorModel(takeIf { condition.vendorModel == null }?.let { "" } ?: condition.vendorModel)
.setPayType(takeIf { condition.payType == null }?.let { "" } ?: condition.payType)
.build()
但是上面的关键代码
takeIf { condition.skuId == null }?.let { "" } ?: condition.skuId
还是有点复杂:
可以修改成:
val cmdbProduct: Cmdb.Product = Cmdb.Product.newBuilder()
.setSkuId(condition.skuId ?: "")
.setFastoneStrategy(condition.fastoneStrategy ?: "")
.setProductLevel(condition.productLevel ?: "")
.setFastoneRegion(condition.fastoneRegion ?: "")
.setVendor(condition.vendor ?: "")
.setProductType(condition.productType?.name ?: "")
.setSystemPlatform(condition.systemPlatform?.name ?: "")
.setFastoneModel(condition.fastoneModel ?: "")
.setFastoneFamily(condition.fastoneFamily ?: "")
.setVendorModel(condition.vendorModel ?: "")
.setPayType(condition.payType ?: "")
.build()
对比takeif和?:
fun main(){
val user=user(1,"sunyuhua")
val username= user.takeIf { user.className==null }?.let { "值为空" } ?:user.className
println("username=$username")
val username2= user.className?:"值为空"
println("username2=$username2")
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sunyuhua_keyboard/article/details/124865842
内容来源于网络,如有侵权,请联系作者删除!