kotlin

kotlin

A tiny module that makes a Jooby application more Kotlin idiomatic.

dependency

<dependency>
  <groupId>org.jooby</groupId>
  <artifactId>jooby-lang-kotlin</artifactId>
  <version>1.5.1</version>
</dependency>

usage

via Kooby class (preferred):


import org.jooby.*

Class App: Kooby({
  get {
    "Hello Kotlin"
  }
})

fun main(args: Array<String>) {
  run(::App, *args)
}

via run function:


import org.jooby.*

fun main(args: Array<String>) {
  run(*args) {
    get {
      "Hello Kotlin"
    }
  }
}

The run function is a type-safe builder that initializes, configures and executes a Jooby application.

idioms

request access

Access to the request is available via a request callback:

{
  get("/:name") {req ->
    val name = req.param("name").value
    "Hi $name!"
  }
}

The request idiom gives you implicit access to the request object. The previous example can be written as:

{
  get("/:name") {
    val name = param("name").value
    "Hi $name!"
  }
}

Reified param, header, body calls:

{
  get("/:name") {
    val count = param<Int>("count")
    count
  }

  post("/") {
    val myobj = body<MyObject>()
    myobj
  }
}

path group

This idiom allows grouping one or more routes under a common path:

{

  path("/api/pets") {

    get { 
      // List all pets
    }

    get("/:id") { 
      // Get a Pet by ID
    }

    post {
      // Create a new Pet
    }
  }
}

class reference

Jooby provides a Kotlin class references where a Java class reference is required.

Example 1: Register a MVC routes

{
  use(Pets::class)
}

Example 2: Get an application service:

{

  get("/query") {
    val db = require(MyDatabase::class)
    db.list()
  }
}

examples

JSON API

The next example uses the jackson module to parse and render JSON:


import org.jooby.*
import org.jooby.json.*

data class User(val name: String, val age: Int)

class App: Kooby({
  use(Jackson())

  get("/user") {
    User("Pedro", 42)
  }

})

fun main(args: Array<String>) {
  run(::App, *args)
}

NOTE: You need the jackson-module-kotlin for Kotlin data classes.

mvc example


import org.jooby.*
import org.jooby.mvc.*
import javax.inject.Inject

@Path("/api/pets")
class Pets @Inject constructor(val db: MyDatabase) {

  @GET
  fun list(): List<Pet> {
    return db.queryPets()
  }
}

fun main(args: Array<String>) {
  run(*args) {
    use(Pets::class)
  }
}

starter project

We do provide a kotlin-starter demo project.

That’s all folks!