Put a little Kotlin sugar in your Java recipes

Yassin Hajaj
Jun 24 · 3 min read
SaltBae seasoning a Java state-of-the-art app with some Kotlinish madness

Introduction

Use the following techniques to mimic Kotlin language features inside of your 100% Java Applications.

Data Classes

Data classes have been created as a feature in Kotlin to manage those classes that only purpose is to hold data.

The lombok library allows us, with the use of a simple annotation, to create a data class from a simple Java class.

Look at the example here under :

Person.kt

data class Person(
var spouse:Person?,
var father: Person?,
var name: String?
)

Person.java

@Data
public class Person {
private Person spouse;
private Person father;
private String name;
}

Setters and getters are added to the class. Your favorite IDE should be able to work with those with a little help on your side :).

One of the differences here are that @Data also includes toString which a Kotlin data class doesn’t implement by default.

@Value could also be used if you want your objects to be made immutable, you’d have to replace the var s by val s in the Kotlin example tho.

Safe Calls

Safe calls are great, because one of their purpose is to make function invocation chaining without risking of having a NPE get thrown at our faces.

Well, Java has kind of the same safety net built-in for this specific scenario. Using Optional.ofNullable(var) , it is totally possible to mimic this behavior and get our one-liners ready for production.

Family.kt

val motherInLawName = person?.spouse?.father?.spouse?.name

Family.java

String motherInLawName = Optional.ofNullable(person)
.map(Person::getSpouse)
.map(Person::getFather)
.map(Person::getSpouse)
.map(Person::getName)
.orElse(null);

Extension Functions

You can use the experimental feature coming with the lombok project allowing you to use extension functions in the same way as Kotlin allows you to do it.

Look at this example here under :

Extensions.java

public class Extensions {
public static boolean isValidNationalRegistryNumber(String target) {
return !isNull(target) && target.matches("\\d{6} \\d{3} \\d{2}");
}
}

CustomerResource.java

@Resource
@ExtensionMethod({Extensions.class})
public class CustomerResource {

@GetMapping("/customer")
public String getCustomer(String nationalRegistryNumber) {
boolean isValid = nationalRegistryNumber.isValidNationalRegistryNumber();
if (!isValid) {
throw new RuntimeException("Invalid nrn !");
}
return "Found";
}
}

CustomerResource.class

@Resource
public class CustomerResource {
public CustomerResource() {
}

@GetMapping({"/customer"})
public String getCustomer(String nationalRegistryNumber) {
boolean isValid = Extensions.isValidNationalRegistryNumber(nationalRegistryNumber);
if (!isValid) {
throw new RuntimeException("Invalid nrn !");
} else {
return "Found";
}
}
}

Ranges

Using the previously seen Kotlin’s @ExtensionMethod annotation, we can implement, by adding an extended function to the Number class, a mechanism quite similar to the ranges in Kotlin.

Ranges.kt

@PostMapping("/guess")
fun guess(guess: Int) {
if (guess in 1..10) {
println("You won!")
return true
}
return false;
}

Ranges.java

@ExtensionMethod({Extensions.class})
...
@PostMapping("/guess")
public boolean guess(Integer guess) {
if (guess.in(1, 10)) {
System.out.println("You won !");
return true;
}
return false;
}

Ranges.class

@PostMapping({"/guess"})
public Boolean guess(Integer integer) {
if (Extensions.in(integer, 1, 10)) {
System.out.println("You won !");
return true;
} else {
return false;
}
}

Conclusion

Mimicking Kotlin in your Java application shouldn’t be a dream anymore. You can certainly have kind of the same features implemented in Java.

I’d suggest you to take a look at what Lombok has to offer on the stable features page, but also on the experimental page.

Yassin Hajaj

Written by

I’m a developer who has a thing for artificial intelligence !

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade