0
  • I'm maintaining a microservice system was written in Kotlin and Spring-boot and at some code, I found !! syntax which i don't know what it meaning:
fun getListOrderStatus(orderStatusAgentRequestDto: OrderStatusAgentRequestDto): ResponseEntity<List<OrderStatusAgentResponseDto>>? {
        val accessTokenAgent = agentAuthService.getAccessTokenAgent()
        val requestUri = UrlBuilder(mposApiEnpoint.orderStatusListRead)
                .addParam(HttpUtils.PARAM_ACCESS_TOKEN, accessTokenAgent!!.accessToken)
                .addParam("page_size", "${orderStatusAgentRequestDto.pageSize}")
                .addParam("order_codes", if (orderStatusAgentRequestDto.orderCodes != null) orderStatusAgentRequestDto.orderCodes.joinToString(separator = ",") else "")
                .addParam("modified_time", "${orderStatusAgentRequestDto.modifiedTime}")
                .addParam("service_id", "${orderStatusAgentRequestDto.serviceId}")
                .toString()
        val restTemplate = RestTemplate()

        return restTemplate.exchange(requestUri, HttpMethod.GET, null, object : ParameterizedTypeReference<List<OrderStatusAgentResponseDto>>() {})
    }

....
....
val status = orderMappingApi.getListOrderStatus(agentRequestDto)
val orderStatus = status.body!![0]
  • The status was the response of a above function. Can somebody please explain to me what !! mean and what its use in this case? Thank in advance!!!
Dattq2303
  • 52
  • 8

1 Answers1

2

!! in Kotlin is the not-null assertion operator. it converts any value to a non-null type and throws an exception if the value is null.

val len = query!!.length

if query is not null it will return its length but if query is null we'll get NPE.

  • It seem like the IDE automatic recommend add it. Can i replace it with ?. syntax? – Dattq2303 May 06 '21 at 04:21
  • 1
    Yes you can replace it with ?. for null safety. In your case orderStatus will be set to status.body[0] if status is not null otherwise it will be set to null but if you use status.body!![0] it will throw NPE if status is null otherwise it will also return status.body[0] – Shivam Sharma May 06 '21 at 12:28