In this recipe we will convert the classes in the controller package to Kotlin.
The RecipesController
contains the REST methods of our Recipes
API, and the RecipesControllerAdvice
catches
exceptions and returns the proper error code and response.
- Convert the
RecipeController
Java files to Kotlin - As the log property was created based on Lombok annotation
@Slf4
, we will have to replace it. Add acompanion object
to the class, and declareval log: Logger = LoggerFactory.getLogger(RecipeController::class.java)
to it - Declare the private
recipeService
property as a non-nullable argument to the primary constructor. This way you can call the members on it without a safe call (?.) or a bang-bang (!!) - Convert
RecipeControllerAdvice
to Kotlin - Use the
listOf()
instead of Java'sList.of()
- When ready, run all tests:
(cd ../.. && ./mvnw clean verify)
The ErrorMessageMapper
is used by the RecipesControllerAdvice
to transforms the error messages from the exceptions
thrown by the application to the body of an error response.
For example, if the client POST
request contains multiple incorrect fields a MethodArgumentNotValidException
is
thrown by the application, because of the constraints put on certain request fields (e.g. @NotNull
, @NotEmtpy
etc.).
The ErrorMessageMapper
will map all the error messages (constraint violations) to a single String
(with a pre-fix),
and creates an RecipeErrorResponse
.
Which gets serialised to JSON
and returned to the client.
-
Convert the
ErrorMessageMapper
Java files to Kotlin. Because this class contains onlystatic
methods, IntelliJ converts it into a singletonobject
-
Refactor both the
toErrorMessage()
method the following way:- Use Kotlin's Collection
extension
functions instead of Java Streams - Assign default values to the optional parameters
- Use
sortedBy()
to sort the messages - Replace the mutable
StringBuilder
by more lean and safejoinToString()
implementation.
- Use Kotlin's Collection
-
When ready, run all tests:
(cd ../.. && ./mvnw clean verify)
- If all tests have passed, continue to the next recipe.