Scala Tutorial
This tutorial demonstrates writing OfficeFloor REST endpoint logic in Scala within a Spring Boot application. Because Scala objects compile to JVM singletons, Scala object methods work directly as OfficeFloor service procedures alongside Java code.
Maven dependency
Add the OfficeFloor Scala support alongside the Spring Boot starter:
<dependency>
<groupId>net.officefloor.scala</groupId>
<artifactId>officescala</artifactId>
</dependency>
Application class
Register DefaultScalaModule as a Spring bean so that Jackson can serialise and deserialise Scala classes in @RequestBody and ObjectResponse:
@SpringBootApplication
class Application {
@Bean
def scalaJacksonModule(): JacksonModule = DefaultScalaModule
}
object Application extends App {
SpringApplication.run(classOf[Application], args: _*)
}
Scala service method
The Scala object method that handles the request uses @RequestBody to receive the JSON request body and ObjectResponse to send the response:
object ScalaService {
def service(@RequestBody request: ScalaRequest, response: ObjectResponse[ScalaResponse]): Unit = {
response.send(new ScalaResponse(s"Hello ${request.message}"))
}
}
REST endpoint
The YAML file routes POST '/scala' to the Scala method via the Scala procedure source. The compiled class name for a Scala object is <ObjectName>\$:
Scala:
resource: net.officefloor.tutorial.scalahttpserver.ScalaService$
procedure: Scala
method: service
Scala data classes
Scala classes work directly as JSON request and response objects once DefaultScalaModule is registered:
class ScalaRequest(val message: String)
class ScalaResponse(val message: String)
Testing
@SpringBootTest
@AutoConfigureMockMvc
class ScalaHttpServerTest {
@Autowired
var mvc: MockMvc = _
@Autowired
var mapper: ObjectMapper = _
@Test
def service(): Unit = {
mvc.perform(post("/scala")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(new ScalaRequest("Daniel"))))
.andExpect(status().isOk)
.andExpect(content().json(mapper.writeValueAsString(new ScalaResponse("Hello Daniel"))))
}
}
Next
The next tutorial covers polyglot JavaScript.

