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

Advertisements

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

Transforming collections – Java 8 Collectors API

Java 8 offers new Stream API that makes handling collections easier and less verbose and error-prone. Stream API offers set of methods for filtering, transforming underlying collection, but our interest is to cover collect(Collector collector) method. This method offers very interesting functionality, such as transforming underlying collection to another collection type, grouping elements of collection, joining elements, partitioning elements…

Let’s get started with an example, and start explaining based on it. I suggest you open new tab with source code so that you can review the code sample while following explanation here. Continue reading

Lightweight strategy pattern in Java 8

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm’s behavior to be selected at runtime. The strategy pattern. defines a family of algorithms, encapsulates each algorithm, and. makes the algorithms interchangeable within that family.

Let’s start straight away with an example. Task is to build an application that would load a user information from arbitrary storage, log user details using arbitrary logger and finally – save user using different persistence options. App should be a Java console application receiving input as command line parameters.

Continue reading

Avoid NullPointerException – use Java 8 Optional

This blog post should start with a popular quote:

Tony Hoare introduced Null references in ALGOL W back in 1965 “simply because it was so easy to implement”, says Mr. Hoare. He talks about that decision considering it “my billion-dollar mistake”.

Instead of dealing with null / not-null references, Java 8 JDK ships with new type: Optional<T>. How to use it?

Continue reading

Java 8 flatMap stream operator

Ladies and gents, let’s see a simple example of Java 8 flatMap method found in Stream API. Definition of flatMap in API doc is:

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)

Say we have a simple Java bean Developer: Continue reading