实体赋值处理null的问题

x33g5p2x  于2022-05-20 转载在 其他  
字(2.2k)|赞(0)|评价(0)|浏览(386)

项目开发中涉及到一个请求实体,如果为空,就设置为"",这样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")

}

相关文章