gpt4 book ai didi

实体赋值处理null的问题

转载 作者:知者 更新时间:2024-03-13 17:28:03 26 4
gpt4 key购买 nike

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

}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com