In Spring with Kotorin-- 2. RestController and Data Class, I added a controller class to enable REST API access. However, the API I added was a very simple application with only GET access.
This time, let's add an API so that it can be accessed by the HTTP method with PUT / POST / DELETE.
Among them, I will introduce the omission of curly braces in one of the ways to write a function in Kotlin.
Spring Dependencies
--API design ――For the sake of clarity, we have not designed the API properly. Each access path is given to each API of GET / PUT / POST / DELETE.
In the API we prepared for GET access earlier, we used the @GetMapping
annotation as follows:
@GetMapping(value = ["/display"])
fun getMessages() : List<Message> {...}
Similarly, PUT / POST / DELETE are defined using @ PutMapping
/ @PostMapping
/ @DeleteMapping
.
@PutMapping(value = ["/insert"])
fun insertMessage(@RequestBody message: Message) : Message {...}
@PostMapping(value = ["/update"])
fun updateMessage(@RequestBody message: Message) : Message {...}
@DeleteMapping(value = ["/delete/{id}"])
fun deleteMessage(@PathVariable(name = "id") id: String): Boolean = {...}
Normally, when defining a function, enclose it in {...}
** curly braces ** and write the expression to be processed in it.
In Kotlin, if there is only one expression, you can omit the curly braces.
Therefore, the following two functions have the same meaning.
With curly braces
@DeleteMapping(value = ["/delete/{id}"])
fun deleteMessage(@PathVariable(name = "id") id: String): Boolean {
return true
}
Braces omitted
@DeleteMapping(value = ["/delete/{id}"])
fun deleteMessage(@PathVariable(name = "id") id: String): Boolean = true
This time, I introduced the description that omits the curly braces in the function, but in Kotlin, you can write various other omitted descriptions, and you can write the code concisely.
In the future, I will continue to explain the parts that can be described concisely while creating applications with Spring.
Recommended Posts