0 boilerplate implementing State pattern in Kotlin

State pattern is pretty nice solution for solving problems related to changing behavior of some component(class) at runtime, which varies depending on current state of that object. Clients of our class having dynamic behavior have an impression that, upon interaction with that class, it seems like there’s different implementation of that object as of that interaction. There’s no magic involved – we’re just using composition, and our dynamic object just delegates call to State object it encapsulates. Interface of State object defines set of actions (methods) that change behavior of our wrapping class (set of actions that cause system to transition). State implementations are those that are in charge of making transitions from State to State.

Here’s an example of coffee machine, that acts differently based on State it’s currently in. Here, CoffeeMachine is our dynamic class, and it encapsulates instance of our CoffeeMachineState interface. We initially set Off implementation of State when starting our coffee machine. Then, our implementations transition the state, based on different actions being performed.

Go ahead – subscribe for more interesting content to come! 🙂

Decorator pattern in Kotlin

If you feel curious how would an implementation of decorator design pattern look like in Kotlin, you came to the right place. This example is just a very basic thing that you then tweak until it’s perfect. You can find decorator definition yourself, but what’s important is that you can compose chain of decorators at runtime and in such a way – you can control runtime behavior of your system.

Liked this one? Subscribe 🙂

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 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