Kotlin Tutorial
This tutorial demonstrates writing OfficeFloor REST endpoint logic in Kotlin within a Spring Boot application. Because Kotlin compiles to JVM bytecode, Kotlin top-level functions work directly as OfficeFloor service procedures alongside Java code.
Maven dependency
Add the OfficeFloor Kotlin support alongside the Spring Boot starter:
<dependency>
<groupId>net.officefloor.kotlin</groupId>
<artifactId>officekotlin</artifactId>
</dependency>
Application class
@SpringBootApplication
open class Application
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
Kotlin service function
The Kotlin top-level function that handles the request uses @RequestBody for the request body and ObjectResponse to send the response:
package net.officefloor.tutorial.kotlinhttpserver
import net.officefloor.web.ObjectResponse
import org.springframework.web.bind.annotation.RequestBody
fun service(@RequestBody request: KotlinRequest, response: ObjectResponse<KotlinResponse>) {
response.send(KotlinResponse("Hello ${request.name} from Kotlin"))
}
REST endpoint
The YAML file routes POST '/' to the Kotlin function via the Kotlin procedure source. The compiled class name for a Kotlin file of top-level functions is <filename>Kt:
Kotlin:
resource: net.officefloor.tutorial.kotlinhttpserver.KotlinLogicKt
procedure: Kotlin
method: service
Kotlin data classes
Kotlin data classes work directly as JSON request and response objects. Jackson's Kotlin module (included via officekotlin) handles serialisation automatically:
data class KotlinRequest(val name: String)
data class KotlinResponse(val message: String)
Testing
@SpringBootTest
@AutoConfigureMockMvc
class KotlinHttpServerTest {
@Autowired
lateinit var mvc: MockMvc
@Autowired
lateinit var mapper: ObjectMapper
@Test
fun service() {
mvc.perform(post("/")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(KotlinRequest("Daniel"))))
.andExpect(status().isOk)
.andExpect(content().json(mapper.writeValueAsString(KotlinResponse("Hello Daniel from Kotlin"))))
}
}
Next
The next tutorial covers Scala.

