FIVE THINGS YOU’LL LOVE ABOUT KOTLIN
3. SENSIBLE CONCISENESS
▸ Immutable by default
▸ Type inference
▸ Data classes
▸ Trailing Lambdas
▸ Infix functions & Operators
▸ DSLs
fun ChatApp(): PolyHandler {
val userCounter = AtomicInteger()
val messages = mutableListOf()
val participants = ConcurrentHashMap()
fun addMessage(new: String) {
messages.add(new)
participants.values.forEach { it.send(WsMessage(new)) }
}
fun newConnection(ws: Websocket) {
val id = "user${userCounter.incrementAndGet()}"
participants += id to ws
messages.map(::WsMessage).forEach { ws.send(it) }
addMessage("$id joined")
ws.onMessage { addMessage("$id: ${it.bodyString()}") }
ws.onClose {
participants -= id
addMessage("$id left")
}
}
val http = BasicAuth("http4k",
Credentials("kotlin", “isgreat"))
.then(static(Classpath()))
val ws = websockets("/ws" bind ::newConnection)
return PolyHandler(http, ws)
}
fun main() {
ChatApp().asServer(Jetty(5000)).start()
}