When you start a new project on the JVM, should you pick Java or Kotlin? Which one should you pick when you have a domain with many rules and nuances that needs to be expressed with as little ambiguity as possible? In short, what if you need to model a rich domain?
In part 1 of this series we compared the ecosystem of both languages, in part 2 we looked at the multiplatform capabilities, in part 3 we had a general introduction to Kotlin syntax and its interop with the Java platform, in part 4 we looked at the safety features of both languages, and in this part we will get into how well the languages support us when we model business domains, before we give a final verdict: should you pick Java or Kotlin?
Language Evaluation Criteria
Programming languages that are good for modelling business domains ideally fulfil the following evaluation criteria:
- Code reads like domain prose
- Safety at compile time
- Interoperability with the platform
- Immutability
- Conciseness
These are roughly in my order of priority. For example, I care more about expressive prose than I care about null safety. The first item, code reads like domain prose, is key to domain modelling and will be the focus of this part. We will not give the other items a dedicated section, as safety at compile time was the focus of part 4, while interoperability and immutability were the focus of part 3. We will still touch these criteria in the following code examples, which will also demonstrate the last criterion: how concise the languages are.
The next chapter will show how we can model a domain with both languages and how close that comes to actual domain prose. Afterwards we will finally tackle the question that this article series has promised since the start: Kotlin or Java? I recommend reading part 3 again if you are not familiar with Kotlin syntax, as the following chapters all build on what was shown there.
The example domain for this part will be Martin Fowler’s video store. This is a store where you could go to rent a thing called a “DVD,” which is a shiny disc that stores videos of all kinds. These discs had to be returned in a timely manner, lest we incur “rental fees.” The fee for the rental changed depending on the video we had rented. ‘Twas the time of “Blockbuster,” long ago, before we could stream all our content.
Code Reads Like Domain Prose
Code is read/parsed more often than it is written/generated. The more clearly we can express domain intent, the less can hide in ambiguity and the easier the code becomes to modify. And that is the point. “The quality of software is defined by our ability to change it” (as defined by Dave Farley). Code that reads like domain prose does double duty here: it is not just executable but also documentation, requiring less context to understand. Programming languages can support us here but which does it better? The following code will try to show that with five simple but typical situations for business logic: modelling a choice, handling nested nulls, making a choice, looping over data, and of course testing the behaviour is correct.
General note: the following code examples favour strong types: a day is modelled as JDay/KDay, not as an int/Int. This style both enriches the semantics of our code and prevents unintentional errors (incompatible types cannot interact). The examples also place the business logic outside of the records and data classes, in an attempt to emulate a data-oriented / functional style. This is a style that seems quite popular today, and something that Java has adopted since JDK 17. Writing this with a rich domain model / object-oriented style, where data is hidden and behaviour is next to the data it works on, is a task for the curious reader.
Modelling a Choice
One situation where Java has really improved with JDK 16+17 is modelling choice. In our video store domain we have three types of rentals that need to be modelled: newly released, children’s and regular rentals. We can model this with sealed interfaces:
sealed interface JRental { // <1>
@Nullable JReturnPolicy returnPolicy(); // <2>
JDay rentedDays(); // <3>
}
record JNewRental( // <4>
JRentalId id, JDay rentedDays
) implements JRental {
@Override
public JReturnPolicy returnPolicy(){
return new JReturnPolicy(
new JDay(2) // <5> mustBeReturnedAfter field
);
}
}
// JRegularRental and JChildrensRental omitted for brevity
JRental <1> is an interface for which exactly three implementations exist: JNewRental <4>, JRegularRental and JChildrensRental. But we can make even more domain rules explicit. A rental can have a return policy but does not have to, the optionality of this being explicit because it is @Nullable <2>. A new rental should be returned after two days <5>. Every rental knows how long it has been rented for <3>. We can model the same in Kotlin with very similar syntax:
sealed interface KRental { // <1>
val returnPolicy: KReturnPolicy? // <2>
val rentedDays: KDay // <3>
}
data class KNewRental(
val id: KRentalId, override val rentedDays: KDay
) : KRental { // <4>
override val returnPolicy = KReturnPolicy(
mustBeReturnedAfter = 2.days() // <5>
)
}
The big difference between those is that nullability <2> is more compact in Kotlin, that inheritance is not written with a keyword but with a colon <4> and that Kotlin has named parameters, which we can use here to make our intent more explicit <5> and make the code more readable without an IDE offering parameter hints.
That concludes how to model choice. Next we will investigate how to handle nested nulls.
Handling Nested Nulls
In Java we can now use the return policy to calculate the lateFee for a rental:
class JRentalService {
// other code omitted for brevity
private JMoney lateFee(JRental rental) {
var policy = rental.returnPolicy();
if(policy == null || policy.mustBeReturnedAfter() == null){ // <0>
return JMoney.ofEuros(0); // <1>
}
return JMoney.ofEuros( // <2>
rental.rentedDays().minus(policy.mustBeReturnedAfter())
.atLeastZero().times(3)
.rawValue() // <3>
);
}
}
The business logic here is actually rather simple: if you have the rental for longer than the policy allows <3> then it costs you a late fee in euros <2>. <1> is just an early return if either the returnPolicy or the mustBeReturnedAfter is null. The example added minus, times and atLeastZero methods to JDay to stay in the type. A .toEuros() conversion method was not added to JDay, because days and euros are not linked semantically, so they should not depend on each other. We do not have to add these methods, however. With rawValue() we can also get the underlying int that is stored inside JDay and rewrite the return to use operators (-, *), as seen in the code below. Personally, I find the following operators easier to read, but do not like the loss of type safety and the additional nesting of Math.max, which is why I stick to the former example.
return JMoney.ofEuros( // <2>
Math.max(rental.rentedDays().rawValue() - policy.mustBeReturnedAfter().rawValue(), 0) * 3 // <3>
);
Eagle-eyed observers may have noticed that the previous code has a bug in highly-concurrent code bases. As discussed in part 4, NullAway assumes methods like returnPolicy are functionally pure, that is they always return the same value given the same parameters on the same instance. If another thread were to modify mustBeReturnedAfter after the two null-checks <0> and the subtraction <3>, then this code would compile fine, but could throw a NullPointerException at runtime. Whether or not that is an actual problem depends on the concurrency and mutability of the data. Highly concurrent and immutable would work fine, for example.
In Kotlin we can write the logic like this:
class KRentalService {
// other code omitted for brevity
private fun lateFee(rental: KRental): KMoney {
val mustBeReturnedAfter: KDay = rental.returnPolicy?.mustBeReturnedAfter
?: return 0.euros() // <1>
return ((rental.rentedDays - mustBeReturnedAfter)
.atLeastZero() * 3) // <3>
.toEuros() // <2>
}
}
We have the same early return if returnPolicy or mustBeReturnedAfter is null <1>. We use the null-safe calls ?. to determine if mustBeReturnedAfter is null and if it is we execute the expression to the right of the Elvis operator ?: which promptly returns. If it does not return we continue and execute the business logic <3>. Note that we are not using rawValue for the subtraction but KDay objects directly, which we can because we have overloaded the minus operator. Then we convert that toEuros <2> with an extension function (the extension function lives outside both KDay and KMoney, avoiding direct dependencies between these two classes). The order — first business logic, then conversion — matches the natural reading order but also the way it executes at runtime, a nice benefit of the Kotlin approach. We will see some other benefits when it comes to making a choice.
Making a Choice
After having calculated the late fee, we can now calculate the price of a rental for a specific renter:
class JRentalService {
// other code omitted for brevity
private JMoney price(JRental rental, JRenter renter) {
var freeDays = renter.isRecentSignup() && renter.freeFirstDays() != null
? renter.freeFirstDays().rawValue()
: 0;
int chargedDays = switch (rental) { // <0>
case JRegularRental regular -> regular.rentedDays().rawValue() - freeDays; // <1>
case JNewRental(_, JDay rentedDays) -> rentedDays.times(2).rawValue(); // <2>
case JChildrensRental(_, JDay(int rawDays)) -> rawDays / 2; // <3>
};
return JMoney.ofEuros(Math.max(chargedDays, 0));
}
}
Here we need to make a choice <0>. The type system knows that JRental only has three implementations, so it knows that we only need to handle these cases. The following case expressions each use a different pattern matching approach (pattern matching since JDK 21 | September 2023; _ for unnamed variables and patterns since JDK 22 | March 2024) so we can see the modelling alternatives.
- The first case matches types, uses method chaining to get the raw value.
- The second case matches one level deeper to the
rentedDaysand uses thetimesfunction to multiply. - The third case matches the innermost pattern, the
rawDays, so it can use primitive division afterward.
Which of these is idiomatic Java is not clear to me. Pattern matching is “only” three years old and record patterns are limited to records, somewhat muting adoption. All three options are presented here, because they could all be idiomatic Java, which makes them a comparison target. In Kotlin the same code would look like this:
class KRentalService {
// other code omitted for brevity
private fun price(rental: KRental, renter: KRenter): KMoney {
val freeDays = if (renter.isRecentSignup && renter.freeFirstDays != null)
renter.freeFirstDays
else 0.days()
val chargedDays = when (rental) { // <0>
is KRegularRental -> rental.rentedDays - freeDays // <1>
is KNewRental -> rental.rentedDays * 2 // <2>
is KChildrensRental -> rental.rentedDays / 2 // <3>
}.atLeastZero()
return chargedDays.toEuros()
}
}
In Kotlin we can make the same choice and, like in Java, the compiler knows we have handled all cases. We do that with a when expression <0>, which has replaced Java’s switch. When is a bit more powerful because it can also work without an argument, allowing us to write longer if–else-chains concisely.
After that we check which case we are handling <1>, <2>, <3> with is, which is Kotlin’s variant of the instanceof keyword. When a type matches, rental is automatically cast to that type. In case <1> for example, rental is of type KRegularRental to the right of the arrow ->. This is known as smart casting. It is less powerful than pattern matching in Java, which is a combination of type check + type cast + deconstruction of the object into its parts, because we only get the first two features. But it is also less wordy, because we do not have to assign new variable names, as the Java cases show. Overall this looks a bit cleaner and less noisy due to smart casts, the overloaded operators and the type-constructing days() and toEuros() extension methods.
With price and lateFee methods introduced, we can now look at how to use them when looping over data.
Looping Over Data
In the next code example we will go over all rentals of a renter to see how much she owes currently:
class JRentalService {
private final Map<JRenterId, List<JRental>> rentals;
public JRentalService(Map<JRenterId, List<JRental>> rentals) {
this.rentals = rentals;
}
public JMoney amountOwed(JRenter renter) {
return rentals.getOrDefault(renter.id(), List.of()) // <1>
.stream()
.map(rental -> price(rental, renter).plus(lateFee(rental))) // <2>
.reduce(JMoney.ofEuros(0), JMoney::plus); // <3>
}
// other code omitted for brevity
}
We first get all rentals of the renter or an empty List.of() <1>. Then we calculate the price and latefee for each rental <2>. Finally we sum it all up with the plus method of the JMoney type <3>. In Kotlin it looks similar:
class KRentalService(private val rentals: Map<KRenterId, List<KRental>>) {
fun amountOwed(renter: KRenter): KMoney = // <0>
rentals[renter.id].orEmpty() // <1>
.map { rental -> price(rental, renter) + lateFee(rental) } // <2>
.sum() // <3>
// other code omitted for brevity
}
In Kotlin we save a couple of lines because we have expression bodies <0> that shorten functions with a single return. We access the rentals of the renter with the overloaded index operator [], a Map<> operation that might return null, and use an extension function to declare that the default in case of null is an empty list <1>. The mapping function <2> is, I think, more readable due to Kotlin’s invocation syntax (map(() -> ) vs map { -> }) and the operator overloading. Summing up the amount is done via the extension function sum <3>, but we could have also used reduce here, depending on developer familiarity.
With the business logic complete, let us look a bit at testing the correctness of the behaviour.
Testing Correctness
Tests should read like domain prose. They should receive the same attention, arguably more, than production code, because they protect and document the intended behaviour. There are a few ways in which our programming languages can support us here — beyond what the test framework provides. In Java a simple business logic test would look like this with JUnit:
@Test
void regular_rentals_should_cost_one_euro_per_rented_day() { // <1>
var renter = aRenter().build(); // <2>
var rental = aRegularRental().rentedFor(new JDay(3)).build(); // <3>
var testee = new JRentalService( Map.of(renter.id(), List.of(rental)) );
var result = testee.amountOwed(renter);
assertThat(result).isEqualTo(JMoney.ofEuros(3)); // <4>
}
Thanks to the JUnit junit.jupiter.displayname.generator.default property, which we set to org.junit.jupiter.api.DisplayNameGenerator$ReplaceUnderscores, the test name <1> will be displayed as regular rentals should cost one euro per rented day. Two builders helped us define what is important to the test: it needs aRenter <2> and aRegularRental that has been rented for three days <3>. The builders also help because we do not have to specify irrelevant details, like what is the name of the renter? After that we can assert the result <4>. In Kotlin the same test, also with JUnit, would look like this:
@Test
fun `regular rentals should cost one euro per rented day`() { // <1>
val renter = aRenter { } // <2>
val rental = aRegularRental { rentedFor = 3.days() } // <3>
val service = KRentalService( mapOf(renter.id to listOf(rental)) )
val result = service.amountOwed(renter)
result.shouldBe(3.euros()) // <4>
}
In Kotlin all function names can be written with spaces between backticks. In production code that is only useful in the rarest of cases. In test code, however, that is extremely useful and actually part of Kotlin’s official coding conventions. We can write sentences with spaces and they read extremely naturally <1>, no JUnit DisplayNameGenerator needed.
How does that work on the JVM? Funnily enough, Bytecode supports spaces in method names.
We can use the type-safe builders (see also part 4) to construct our test data in a readable fashion <2, 3> and we can also use extension methods effectively. shouldBe is a built-in test framework extension method to compare all types <4>. We can also easily add our own comparison methods if a domain-specific method is needed as extension methods are a language feature that everyone is free to use. Anyone who has ever tried to add a custom comparison method to AssertJ, knows that this is not quite as easy in Java.
Kotlin kontra Java Summary
When you start a new project on the JVM, should you pick Java or Kotlin? If we look at the business modelling we get the following table:
| Criteria | Java | Kotlin | Comment |
|---|---|---|---|
| Code reads like domain prose | ●●○ | ●●● | Java has powerful modelling capabilities with records, sealed types and pattern matching. Kotlin has, arguably, more readable smart casts, built-in operator-overloading (==, in, is), extension functions that allow modelling in reading order, and expressive type-safe builders. |
| Safety at compile time | ●●○ | ●●◐ | Memory safety is provided by the JVM, thread safety is mostly a developer responsibility in both languages. In Java null safety can be achieved via compiler plugin and diligent developers. Kotlin is designed with null safety from the beginning, has stronger runtime guarantees and it also feels more ergonomic to work with nullable types. Neither language has custom string templates. |
| Interoperability with the platform | ●●● | ●●◐ | Java has perfect interoperability with the platform, as it was designed for it. Kotlin is designed with interoperability in mind but there are a few cases where application developers notice a certain drop of comfort and more cases where library developers have to be wary. |
| Immutability | ●●○ | ●●◐ | Java has made great strides toward immutability with records but its immutable collections still provide no type safety. In Kotlin an immutable collection is type-safe as it has no mutating operations in the interface. Other languages (e.g. Clojure) provide even better immutability, however. |
| Conciseness | ●●○ | ●●● | Records, sealed types, switch expressions and pattern matching have made Java into a much more concise language. Kotlin is still more compact — constructors with built-in field assignment, versatile built-in extension functions like .let{} and method expression bodies help here — but the gap has lessened significantly. |
Code should read like domain prose is arguably the most important criterion for a language focused on expressing business logic. Both languages score well here. The language features that Java has pursued (records, sealed types and switch expressions with JDK 17; record patterns with JDK 21) clearly have paid off. Kotlin is still ahead in the expressiveness of the language, but there are some things on the horizon that will change the summary within the next five years.
Kotlin or Java?
Should you pick Java or Kotlin in 2026? The ecosystem summary (part 1) showed no major drawbacks for either language and this modelling summary is equally positive for both languages. So unless you are interested in multiplatform development (where Kotlin has a clear lead, see part 2), or are not able to upgrade to newer JDK versions (which would make Kotlin the clear winner as it can compile the newest features down to JDK 8), the choice on the JVM is a close race.
For me Kotlin still wins because immutable collections in Kotlin have better type safety, because I can model type-safe builders, because its null safety provides much stronger guarantees than Java, and because of its compact expressiveness which allows me to write code that reads like domain prose.
This does not mean that Kotlin is without flaws. The appendix lists some of the pain points, in case you are interested. It also does not mean that this outcome will be the same in the next five years. Both languages are going to evolve and this comparison will look different in five years. There are exciting times ahead. JDK 28 (March 2027) will add a preview of the long-long-awaited value objects, and there is a draft which would add null guarantees to the JVM (“Null-Restricted and Nullable Types” draft). Kotlin has recently added context parameters (Kotlin 2.4, June 2026) which are more flexible function receivers and might soon add error union types. Kotlin won the race in 2026 but Java might take the crown in 2031.
Appendix – How Kotlin Might Trip You
This is a supplementary section that collects the ways in which Kotlin can surprise you or cause friction. We went over the most important ones in the article series but have not collected them in one place. Doing so also gives us the possibility to discuss some additional ones that are minor pains but have not found mention yet.
First the most important ones, paired with why they are not a deal-breaker:
- Kotlin expects developers to continuously update. Migration ergonomics are good though (part 1).
- Kotlin has far fewer practising developers than Java. Kotlin provides a very good learning curve though (part 1).
- Kotlin has operator overloads. Java did not include them due to fear of misuse. I find this concern unwarranted in Kotlin because we do not directly overload the operator, we overload a semantic name. We overload
divnot/. That gives us a semantic test: We can speak the code and check if it makes sense (part 3). - Kotlin has great interop with Java but there are some situations where you run into problems (part 3).
- Java serialisation libraries and ORM mapper sometimes require a no-argument constructor which means we can no longer trust the
nullmarker of our code. - Java can have
nullmarkers but there is no guarantee that they are enforced, which means we cannot trust them in Kotlin code. - Kotlin has no
statickeyword. Insteadstaticfunctions are modelled via a so-calledcompanion objectand a special@JvmStaticannotation. If a Java library or framework requires countlessstaticfunctions in our Kotlin code, we are going to be annoyed. The code is not hard to write, it is just cumbersome.
- Java serialisation libraries and ORM mapper sometimes require a no-argument constructor which means we can no longer trust the
Besides these, we also have some things in Kotlin that have not found a mention yet:
- Kotlin has no checked exceptions. If a Kotlin function calls a Java function that is annotated with
throws, it is treated like aRuntimeException. We do not have to catch it. Given how divisive checked exceptions are, this might actually be a benefit to some. It has never been a huge problem for me but it has certainly tripped me one or two times. - Kotlin provides many more locations to place business logic than Java. In Java we either put the logic in the domain
class(e.g. insideJRental) or in a service class (e.g.JRentalServicehas the logic andJRentalonly has the data). In Kotlin we have many more choices and those can create modelling confusion:- Inside a domain
class - Inside a service
class - An extension function for a domain
class - As a top-level
funto which we pass a domainclass - As a top-level
funwithcontextparameter (Kotlin 2.4, June 2026) to which we pass a domainclass
- Inside a domain
- Kotlin allows multiple top-level classes and functions in the same file. Java simplified the rules to one file = one
publictop-level class. In Kotlin a file can contain any permutation ofclassandfunand they can all bepublic. - Kotlin has
try,catchandfinallybut no try-with-resources. In Java we can writetry (FileReader fr = new FileReader(path)){ /* reading code here */ }and theFileReaderis automatically closed after the block. We can addcatch(){}to handle exceptions during file reading andfinally {}to do some final cleanup. In Kotlin the equivalent isnew FileReader(path).use{ /* reading code here */ }, which will also close theFileReaderafter the block. This is good until we want to handle exceptions. Then we have to wrap the.use {}block inside atry–catchblock. In Java the code is all on the same indentation level, in Kotlinuse {}is one level deeper. It is not horrible but it feels like a step back from a conciseness standpoint. - Kotlin has no package private modifier. In Java we have four visibility modifiers. If we do not write an explicit modifier, then the
classis considered package private. Such aclasscannot be reached from outside thepackageit is in. That gives us an easy way to create components where only a fewclasses are visible to outside code (this is called package-by-component). In Kotlin this modifier does not exist. There is onlypublic,privateandinternal. - Kotlin’s
internalvisibility modifier is not useful in practice. Aclassmarked asinternalshould only be visible inside its module (a set of Kotlin files compiled together, e.g. a Gradle or Maven project). This is really useful to have but unfortunately cannot be achieved without JVM support. In the endinternalstill becomespublicin bytecode. What the Kotlin compiler does is to mangle the name, e.g. adds the postfix$module_nameto method names, so they become harder to call from Java. This is a bit of a shame, given that Java does have a module system since JDK 9, which would have madeinternalactually possible. In practice I have never used theinternalvisibility modifier.