Java and Kotlin’s interoperability

This post is part of a series of posts about why I’m considering Kotlin for my new projects where I would normally choose Java. If you haven’t read the other posts, check them here: Let's talk about Kotlin?

Igor Leal
2 min readDec 15, 2017

Starting the series about the benefits of Kotlin, I think I should talk about its interoperability with Java. If you are reading this and thinking about using Kotlin, chances are you are familiar with Java, so you will be able more than glad to see that you can use any library you love from Java into your Kotlin code. You can even write a Java code inside your Kotlin project, even though there is no agreement wheter this is good or bad, talking about manutenability, readability, etc. But the thing is, Kotlin was built to interoperate with Java.

Here’s a simple example of a class in Kotlin where I wanted to use the class Date, from java.util and Instant from java.time:

import java.time.Instant
import java.util.Date

class Person(val name: String,
val birthDate: Date,
val photoUrl: String,
val address: String) {

private fun isBirthdateValid() {
birthDate.toInstant().isBefore(Instant.now())
}
}

This is a very simple example, but it shows how you can still get the best of Java while working with Kotlin. Going one step further, you can think about building a Spring Web Controller in Kotlin following the same idea. You’d have something like:

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/person/rest/v1")
class PersonController() {

@GetMapping
fun getPersons() {
// TODO Your code goes here
}

@GetMapping("/{personId}")
fun getPersonById(@PathVariable personId: Long) {
// TODO Your code goes here
}

}

Pretty good, right?

Last but not least, you can even write a Java class in your Kotlin project in case you need it and just use it. Something like this:

import java.time.ZoneId;
import java.util.Date;

public class DateUtil {

public static Date getFirstDayOfTheMonth(Date date) {
return new Date(date.toInstant().atZone(ZoneId.systemDefault()).withDayOfMonth(1).toInstant().toEpochMilli());
}

}

and

import java.util.*

class MyService() {

fun getPerson(startDate: Date, endDate: Date) {
val filterStartDate = DateUtil.getFirstDayOfTheMonth(startDate)
// TODO Rest of the code
}

}

I know that this wouldn’t make you consider Kotlin for your next project, because if the idea is to use Java code, just stay on Java, right? But the idea here is to have like a "backup plan", where you can get the best of two worlds.

In the next posts I’ll get into the real benefits that will make you consider start writing your own Kotlin code.

--

--