Extension functions in kotlin

Kotlin language recently gained some traction owing to Google promoting it as a primary language for writing android apps. Kotlin has already been for a while in production owing to it’s creator JetBrains incorporating it in own tools, such as Intellij IDEA and so forth.

One, amongst many other neat features, is extension functions. In depth documentation can be found on official kotlin website.

About extension functions

In short – extension functions provide us useful tool to extend any existing class, no matter if it’s part of JDK, some 3rd party library or even own, custom ones.

Example, taken from this project, is the following one:

fun Random.betweenInclusive(lower: Int, upper: Int) = this.nextInt(upper - lower) + lower

Here we extend java.util.Random class from JDK, with betweenInclusive(lower: Int, upper: Int) extension method. This method helps us generate random integer between two numbers, lower and upper bounds, inclusive. Project contains couple of useful extension functions, implemented in rs/dodalovic/extension_functions/Students.kt kotlin file. Other examples are extending List<Student> with additional capabilities, taking advantage of functional programming applied on collections. Continue reading

Kotlin powered Spring Boot app consuming NBA Rest API

Ladies and gents, once again I’m sharing some sample app, this time we are building sample Spring Boot app implemented in Kotlin, talking to http://data.nba.net/ API to help us get some interesting, NBA related data. In this case we’re just listing NBA teams, but you extend this sample even further.

Creating project skeleton

The easiest way to create project skeleton is to navigate directly to Spring Boot Initializer website and download pre-configured project. In case you like kotlin – you can choose it from drop down with supported languages. If you’re using Intellij or Spring Tools Suite, you can achieve the same from within your IDE.

Application entry point

KotlinNbaApplicaiton.kt is our application entry point, it’s just a standard kotlin class containing main method and being annotated with @SpringBootApplication.

package rs.dodalovic.nba

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class KotlinNbaApplication

fun main(args: Array<String>) {
    SpringApplication.run(KotlinNbaApplication::class.java, *args)
}

Handling request with TeamController

Continue reading

Sending mail via gmail using Kotlin and commons-mail library

Continuing series of blog posts related to kotlin, today we’ll together make a sample application showing us how we could automate email sending – using kotlin. Example is quite simple, and surely – you can enhance it with own features. Application mostly demonstrates compact kotlin syntax, as well as full compatibility with Java or 3rd party libraries (in this case commons-mail library).

Let’s first take a look at our script:

package mail

import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.HtmlEmail
import java.net.URL

fun main(args: Array<String>) {
    val senderEmail = args[0]
    val password = args[1]
    val toMail = args[2]

    val email = HtmlEmail()
    email.hostName = "smtp.googlemail.com"
    email.setSmtpPort(465)
    email.setAuthenticator(DefaultAuthenticator(senderEmail, password))
    email.isSSLOnConnect = true
    email.setFrom(senderEmail)
    email.addTo(toMail)
    email.subject = "Test email with inline image sent using Kotlin"
    val kotlinLogoURL = URL("https://kotlinlang.org/assets/images/twitter-card/kotlin_800x320.png")
    val cid = email.embed(kotlinLogoURL, "Kotlin logo")
    email.setHtmlMsg("<html><h1>Kotlin logo</h1><img src=\"cid:$cid\"></html>")
    email.send()
}

Continue reading

Factory method pattern in Kotlin

Ladies & Gents, Kotlin language can come quite handy write concise and expressive code, without too much boilerplate, while keeping all advantages of being JVM citizen. Let’s quickly peek into example of creating Factory method creational design pattern implementation.

package patterns

interface Gadget {
    fun play()
    fun getInfo()
}

enum class Purpose {
    FUN, WORK
}

class GadgetFactory {
    companion object {
        fun createGadget(purpose: Purpose): Gadget = when (purpose) {
            Purpose.FUN -> object : Gadget {
                private val model = "XBox One S | year: 2016"
                override fun getInfo() {
                    println(model)
                }

                override fun play() {
                    println("I'm having great fun playing $model")
                }
            }
            Purpose.WORK -> object : Gadget {
                private val model = "Macbook Pro 2015 | year: 2015"
                override fun getInfo() = println(model)
                override fun play() {
                    println("I'm working hard using my $model")
                }
            }
        }
    }
}

val purpose: String = args[0]
val gadget = GadgetFactory.createGadget(when (purpose) {
    "FUN" -> Purpose.FUN
    "WORK" -> Purpose.WORK
    else -> throw IllegalArgumentException("No gadget for such purpose :(")
})

println("\n**** GADGET INFO ****\n")
gadget.getInfo()

println("\n**** PLAYING GADGET ****\n")
gadget.play()

Example demonstrates simple case where user enters which kind of Gadget she/he wants via command line argument, and based on value provided, he gets back some kind of Gadget dynamically instantiated. Continue reading

Strategy pattern example with Kotlin scripts

I thought it would be nice to use advantages of kotlin language to showcase strategy pattern implementation. In order to get the example running – we need to install kotlin binaries (installation). I’m running simple kotlin script in this example.

Having scripting support it makes it very easy to fire up some process with full kotlin language capabilities. You could use it to do some kind of administrative tasks in your business environment.  Continue reading

Microservices with Spring Boot, Netflix Zuul, Kotlin, Docker and MongoDB

Recently I’ve started playing with Kotlin programming language, and wanted to give it a try.

Kotlin gives us possibility to write quite concise code, such as:

@RestController
class UsersController(val userRepo: UserRepository) {

    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/users/{userId}")
    fun getUser(@PathVariable userId: String): UserDTO {
        return userRepo.findOne(userId).toUserDTO()
    }
}

You can find and download source code from GitHub. Readme file there explains how to start & use services. docker-compose comes quite handy to start / shutdown all the services with simple commands and orchestrate them via docker-compose yaml configuration file.

I’ve built sample, small microservice, composed of some kind of simple api-gateway or proxy server, implemented using Spring Boot and Netflix Zuul library for proxying requests to downstream servers.

Continue reading