To make your Kotlin code more idiomatic, you can simplify the chaining of let calls and reduce nesting by directly accessing the regex groups. Here's a refactored version that maintains readability and leverages Kotlin's nullable chaining effectively:
private fun extractDartyOrderId(dartyApiException: DartyApiException): DeliveryAppointmentId? =
ORDER_ALREADY_CREATED_REGEXP.find(dartyApiException.message)
?.groups["deliveryAppointmentId"]
?.value
?.let(::OrderId)
?: run {
logger.error { "Cannot extract darty order id from ${dartyApiException.message}" }
null
}
Explanation:
-
Regex Matching:
ORDER_ALREADY_CREATED_REGEXP.find(dartyApiException.message): Attempts to find a match in the exception message.
-
Accessing the Group:
?.groups["deliveryAppointmentId"]?.value: Safely accesses the deliveryAppointmentId group from the regex match. If the group isn't found or the value is null, the chain proceeds to the ?: block.
-
Mapping to OrderId:
?.let(::OrderId): If the deliveryAppointmentId value is present, it's passed to the OrderId constructor.
-
Handling Failure:
?: run { ... }: If any of the above steps fail (i.e., the ID isn't extracted), it logs an error and returns null.
Benefits of This Approach:
-
Readability: By flattening the nullable chain, the code becomes easier to read and understand.
-
Conciseness: Reduces unnecessary nesting, making the flow of data clearer.
-
Idiomatic Usage: Utilizes Kotlin's powerful nullable handling and scoping functions (let and run) effectively.
Alternative Using a when Expression
If you prefer using a when expression for better readability, especially when handling multiple cases, you can refactor the function as follows:
private fun extractDartyOrderId(dartyApiException: DartyApiException): DeliveryAppointmentId? {
val message = dartyApiException.message
val match = ORDER_ALREADY_CREATED_REGEXP.find(message)
return when {
match?.groups["deliveryAppointmentId"]?.value != null -> {
OrderId(match.groups["deliveryAppointmentId"]!!.value)
}
else -> {
logger.error { "Cannot extract darty order id from $message" }
null
}
}
}
This version uses a when expression to handle the presence or absence of the deliveryAppointmentId, which can sometimes enhance clarity, especially with more complex logic.
Choose the style that best fits your project's conventions and team preferences.