Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
Java to Kotlin

Java to Kotlin

A Refactoring Guidebook
Move a live Java system toward Kotlin without betting the project on a rewrite.
by Duncan McGregor 2021 422 pages
4.58
33 ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Follow Kotlin's grain: transform immutable values instead of translating Java syntax

Syntax is only the start. The book uses the grain of a language to mean the habits, libraries, tools, and design choices that make some approaches natural and others awkward. Kotlin favors explicit nullability, immutable data transformations, and functions that can live outside classes. An automatic Java conversion changes syntax, but can leave a Java-style design intact, complete with needless mutable state and boilerplate.

Design for the destination. A Java 1.0 sum required custom function objects and extensive setup; in Kotlin, the same idea fits in a compact expression. The broader lesson is not that shorter code is always better. It is that code aligned with its language needs fewer workarounds and is easier to compose, analyze, and maintain.

Analysis

What's striking is that language features function like a set of professional defaults. A good default lowers the cost of a sound decision, which is why Kotlin's concise value types and null-aware types can influence architecture, not just keystrokes. Yet a language's grain is not a law of nature: performance constraints, team expertise, and existing APIs can make a less idiomatic choice correct. The useful question is not whether code looks Kotlin-like, but whether its structure makes behavior and risk easier to see.

Convert Java in small, tested steps, not a risky rewrite

Keep the system working. The authors introduce Kotlin into business-critical Java projects while features continue to ship. They begin with a small, low-dependency value class, then convert classes when new work touches them. IntelliJ helps transform code across the language boundary, while tests check that each step preserves behavior.

Expand, then contract. This refactoring technique adds a new interface, migrates callers one by one, and removes the old interface when unused. Small, focused commits make failures easier to locate with tools such as Git bisect. The temporary duplication is intentional, but should not become permanent. A practical starting point depends on why the team chose Kotlin, where the code hurts most, and how the project is organized.

Analysis

This approach resembles a safe migration in database engineering: introduce a compatible path, move users gradually, then retire the old representation. The parallel is useful because it emphasizes operational risk, not just code elegance. Reversibility also changes team behavior: when a step is cheap to undo, developers can test ideas rather than defend a grand rewrite. The method does depend on adequate tests and a build that can handle both languages. Without those, small steps still help, but confidence must come from additional characterization tests and careful review.

Make shared data immutable; move mutation to narrow boundaries

Limit who can change things. A mutable preferences object shared by an application and several views can leave one view displaying stale values, make equality unstable, and complicate threading. The refactoring replaces it with an immutable value: a view receives preferences and returns an updated copy, while the application owns the single mutable reference that changes.

Treat shared collections the same way. In Travelator, sorting a route's list in place silently changed the departure location used elsewhere. Kotlin's `List` prevents mutation through that reference, but it is only a read-only view: Java or another mutable alias may still change the underlying list. A data class is also unsafe when its properties must preserve an invariant, because generated `copy` can create invalid combinations, as with money amount and currency precision.

Analysis

The key distinction is not mutation versus no mutation, but local versus shared mutation. This resembles ownership disciplines in systems programming: fewer aliases mean fewer places that can invalidate an assumption. Copying values can also make undo, concurrency, and testing simpler. Still, immutability has costs, including allocation and awkwardness in user interfaces built around live updates. The authors' strategy is strongest as a default for domain data, not as a prohibition on controlled mutation where identity or immediate coordination is the actual requirement.

Separate calculations from actions to make refactoring safer

A calculation depends on inputs. Given the same values, it returns the same result and does not alter shared state. An action depends on when or how often it runs, because it reads or changes something outside its local computation. The distinction explains why pure transformations are easier to test, cache, rearrange, and reason about.

Move time to the edge. Travelator's current-trip lookup called `clock.instant()` inside a collection filter, so each trip could be judged against a slightly different time. The team passes one timestamp through the call chain and obtains it at the HTTP handler, the interaction's entry point. Tests no longer need a fake clock. A 2015 batch of failing tests also taught the authors that hard-coded dates stop being reliable when the calendar catches up.

Analysis

This distinction connects to referential transparency, the property that lets an expression be replaced by its value without changing behavior. It also clarifies a practical limit: systems exist to perform actions, so eliminating effects is neither possible nor desirable. The design goal is to concentrate them where inputs enter and outputs leave. Some services are only effectively stable within one request, not truly pure. Naming that scope prevents functional vocabulary from promising stronger guarantees than the system actually provides.

Let Kotlin's types carry absence instead of wrapping Optional

Make missing values visible. Java code often communicates absence through convention, annotations, or `Optional`; each requires callers to learn a separate practice. Kotlin expresses it in the type itself: `Leg` means a value is expected, while `Leg?` means it may be absent. The compiler then requires nullable values to be handled, and nonnull Kotlin parameters receive checks at the Java boundary.

Migrate without breaking Java. The authors keep an `Optional`-returning method while adding a nullable version, move Kotlin callers to the new method, and delete the adapter when it has no clients. Kotlin's safe-call and Elvis operators make nullable flows concise. The not-null assertion can still throw, so it is best treated as an exceptional escape hatch, not a replacement for deliberate handling.

Analysis

Encoding absence in a type reduces the gap between documentation and what the compiler can verify. That is a meaningful reliability gain, especially in large call graphs where conventions are easy to forget. The migration example also shows that interoperability is a design constraint, not an afterthought. Kotlin cannot make Java callers safe by itself: platform types and legacy APIs can still introduce nulls. The strongest boundary is therefore explicit, with nullable results where absence is real and prompt validation where untrusted Java enters.

Use extensions and properties to add readable operations without bloating core types

Put operations where they read naturally. Kotlin extension functions let a top-level function be called with method-like syntax, such as a trip converting itself to a calendar event. They improve discoverability in the IDE without changing the original type. The book uses them to turn Java utility methods into operations on collections, strings, and domain values. Extensions are statically selected, however, and cannot access a type's private members or provide runtime polymorphism.

Choose property syntax carefully. A cheap value derived only from an immutable object's data, such as a person's full name, suits a computed property. Age depends on today's date, and a costly hash may be expensive to calculate, so these are better as functions. When a class merely wraps a collection to host operations, Kotlin may allow the wrapper to become a type alias and the operations to become extensions.

Analysis

Extensions offer a useful middle path between putting every behavior on a central domain class and scattering utilities that are hard to find. They resemble modular capabilities: a feature can add operations near its own code without forcing unrelated modules to depend on them. That flexibility can also fragment an API if extensions proliferate or imports hide which behavior is available. Teams benefit from clear package boundaries and naming conventions. Property syntax deserves the same discipline, because convenient access can disguise time dependence or expensive work.

Choose eager lists or lazy sequences by data size and consumption

Use the simplest pipeline that fits. Kotlin `Iterable` operations such as `filter` and `map` are eager and create intermediate collections. For small, in-memory data, this is often straightforward and fast. A `Sequence` evaluates transformations lazily, avoiding intermediate lists and allowing operations such as taking items only until a stopping condition.

Check how many times input can be read. A sequence backed by a collection may be reusable, but one backed by an iterator, file, or network source may be consumable only once. The type does not reveal which case applies. The authors recommend designing sequence algorithms as one-pass operations and testing with `constrainOnce()`. Java streams remain a sensible choice when existing code benefits from their parallel processing or large-scale optimizations.

Analysis

This is a reminder that laziness is a resource strategy, not an automatic performance upgrade. It trades allocation for deferred work and hidden consumption state. That tradeoff resembles streaming data systems, where backpressure and single-pass guarantees matter as much as transformation syntax. Benchmarks should decide close performance questions, especially for small collections. More importantly, tests should model production inputs: a list-backed sequence can conceal bugs that appear only when a file-backed sequence cannot be replayed.

Pass only required behavior as functions, not oversized interfaces

Narrow the dependency. Travelator's recommendations component depended on interfaces offering seven operations, though it used only two. Replacing those dependencies with function types made the required capabilities explicit: one function finds nearby destinations, and another calculates distance. Callers can supply a method reference, lambda, or object that implements the function type.

Simplify tests as well. The tests first stop mocking entire service interfaces, then represent expected lookups with maps from locations to destinations and location pairs to distances. Capturing those maps in a fresh subject for each test turns stateful setup into a clear input-to-output check. Function types reduce interface coupling, but method-reference indirection can make IDE tracing less direct. When clients need several tightly related operations, an interface or a named group of functions may communicate better.

Analysis

The design principle resembles capability-based security: give a component only the authority it needs, rather than a broad object that can do much more. That can reduce accidental coupling and make tests more declarative. The tradeoff is semantic labeling. An interface method named send tells a reader more than an anonymous function with a generic signature unless the function is carefully named and kept near its use. A narrow dependency is valuable when it clarifies responsibility, not merely because functions are fashionable.

Return typed failures for expected errors, and keep I/O at the edges

Make predictable failure part of the result. Kotlin does not enforce Java checked exceptions. For expected failures, such as a duplicate customer or malformed spreadsheet row, the authors use a result type with success and failure cases. A sealed failure hierarchy lists the known problems, and exhaustive `when` expressions make new cases visible to callers. Nullable results work when the reason for failure does not matter; exceptions remain useful for programmer errors and unexpected failures.

Separate computation from I/O. The report generator becomes a transformation from input lines to output lines, leaving file access to the command-line entry point. When large files make full lists too costly, sequences stream input and output, while the outer layer handles I/O exceptions. Moving I/O outward reduces the code that must reason about both side effects and environmental failure.

Analysis

Typed failures improve local reasoning because callers can see and handle the errors a function promises to produce. This resembles algebraic data types used in languages that make failure an ordinary value. The boundary matters: catching every exception and converting it into a generic failure can hide defects, while exposing low-level database details can overcouple business logic. A good error type reflects the caller's decisions, not merely the implementation's exception list. Streaming also complicates purity, since failures may occur during iteration rather than when a sequence is created.

Replace collection wrappers when they add names but no behavior

Use the collection directly when it is the model. Java's mutable collection APIs make sharing risky, so a `Route` class wrapped a list of journeys, exposed indexed access, and accumulated route operations. After migration, Kotlin's read-only collection interface and extension functions made it possible to move those operations out of the wrapper. A `Route` could then be a type alias for `List<Journey>`, letting clients use the full collection API.

Keep real distinctions. A type alias is only another name, not a new runtime type, so it cannot enforce a separate identity or invariant. An itinerary that has an ID as well as a route still deserves a data class; delegation can let it support route operations without hiding its collection. The book's point is not to avoid classes, but to avoid classes whose only job is to conceal useful standard types.

Analysis

This is a strong challenge to the assumption that every domain noun deserves a custom class. Standard collections bring mature operations and compose naturally with transformations. Yet a wrapper can be valuable when it enforces invariants, marks a genuine domain boundary, or carries identity. Removing it should therefore follow analysis of what clients rely on, not a blanket preference for fewer types. A type alias improves ergonomics but sacrifices nominal safety, a cost that matters when two lists with identical element types mean different things.

Choose sealed hierarchies when operations change more often than data types

Design for the likely direction of change. Open polymorphism makes it easy to add new implementations while keeping existing operations stable. In Travelator, that suited itineraries when new item types were common. As features multiplied, however, the shared item interface kept gaining methods for maps, calendars, descriptions, and costs, creating coordination and coupling.

Make known cases exhaustive. A sealed class restricts the set of direct subtypes, allowing a `when` expression to handle every case and prompting a compile error when a new subtype is introduced. Feature-specific operations can then live as extension functions outside the core model. This is safer than scattered `instanceof` checks, but it shifts the maintenance burden: adding a new item type means updating the operations that handle the hierarchy.

Analysis

The choice is an evolution wager: which axis is more likely to vary, the set of cases or the operations applied to them? Sealed hierarchies make an implicit assumption explicit and enlist the compiler as a reviewer. This resembles exhaustive pattern matching in algebraic data type systems. The wager can change as a product matures, so architecture should be revisited when change patterns shift. Neither polymorphism nor sealed classes are universally superior; the relevant evidence is the history and expected location of change.

Analysis

The book's most useful contribution is not a catalog of Kotlin syntax. It is a method for changing the shape of a system while keeping it operational. The authors repeatedly take a Java design that relies on mutable objects, broad interfaces, or hidden effects, then expose its assumptions through small refactorings. The examples make a larger claim concrete: Kotlin becomes valuable when its type system, standard library, and tooling reinforce a design that Java made laborious.

The central engineering move is scope control. Shared mutation, time reads, I/O, and expected failures are not denied; they are moved to narrower boundaries. Inside those boundaries, code can be expressed as transformations over values. That makes behavior easier to test and gives refactoring more freedom. The parallel is to modular risk management: a local failure is easier to isolate than a failure whose effects are distributed through shared state.

The argument is pragmatic rather than doctrinal. Kotlin collections are read-only views, not necessarily immutable objects. Sequences may be single-use. Function types can weaken navigation and names. Data classes can expose invalid states through copying. These limits strengthen the book's larger point: a language feature is not a guarantee by itself. Safety emerges from a fit between type choices, team conventions, tests, and boundaries.

One important qualification is that simpler source does not always mean simpler systems. More extensions can make behavior harder to locate; more result types can create translation work across layers; eager immutable copies can be costly. The authors acknowledge many of these tradeoffs through examples rather than pretending to offer universal rules. Their lasting test is whether a design makes change safer and behavior more legible. For Java teams, that turns Kotlin adoption from a syntax migration into an ongoing practice of discovering which assumptions deserve compiler support and which can remain local conventions.

Summary in 30 Seconds
Migrate Java code in small, tested changes so the system keeps working and failures stay easy to locate. Prefer immutable values and pure calculations, while keeping shared mutation, time reads, and I/O at narrow boundaries. Use Kotlin's nullable types to make absence explicit, and model expected failures as typed results. Choose eager collections or lazy sequences according to data size and reuse, and keep dependencies limited to the behavior each component needs.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.58 out of 5
Average of 33 ratings from Goodreads and Amazon.

Java to Kotlin receives high praise from readers, with an average rating of 4.60 out of 5. Reviewers appreciate the book's approach to guiding Java developers towards Kotlin, explaining language differences and refactoring techniques. The authors' pragmatic view on programming and focus on best practices are commended. Readers find value in the book's discussion of "language grain" and its practical examples. While some found early chapters challenging, most agree it's an excellent resource for Java developers interested in Kotlin, offering insights beyond basic language transition.

Your rating:
4.72
85 ratings
Want to read the full book?

Glossary

the grain of a programming language

Its natural design tendencies

The grain is the way a language's features, libraries, tools, and accumulated conventions make some styles of programming easier and others harder. The authors argue that Java and Kotlin have different grains: Java historically encouraged mutable objects and class-bound functions, while Kotlin more readily supports immutable values, null-aware types, and composable functions.

calculation

A stable input-output computation

A calculation returns the same result for the same inputs and does not depend on when it is called or change shared state. Its inputs include parameters and any immutable receiver data it reads. Calculations are comparatively safe to repeat, cache, test, and rearrange because their behavior is not tied to timing or external effects.

action

A time-dependent effect

An action is code whose behavior depends on when or how often it runs, usually because it reads or changes mutable state, performs I/O, or interacts with an external system. Calling a database, printing text, or reading the current time are examples. Actions restrict refactoring because moving or repeating them can change observable behavior.

Expand-and-Contract Refactoring

Migrate interfaces without a break

This technique changes an API in stages. First, add a new interface or implementation while preserving the old one. Next, move clients to the new form, ideally in small tested steps. Finally, remove the old form once it has no callers. The temporary duplication supports continuous operation during a migration, but should not be left indefinitely without a reason.

extension function

A function called like a method

An extension function is defined outside the class it appears to extend, but Kotlin lets callers use method-like syntax on a receiver. It can make operations discoverable in IDE completion without modifying the original class. Extensions do not gain access to private members and are resolved using the receiver's static type, so they do not provide runtime polymorphism.

Sequence

A lazy value pipeline

A Kotlin Sequence represents values processed lazily: intermediate operations such as filtering and mapping run when a terminal operation requests results. This can avoid intermediate collections and support input larger than memory. Sequences may be backed by reusable collections or by single-use iterators and resources; the type does not distinguish these cases, so algorithms should generally consume a sequence once.

type alias

An alternate type name

A Kotlin type alias gives an existing type another name, such as naming List<Journey> as Route. It can clarify domain intent without adding a wrapper class or changing the underlying representation. It does not create a distinct runtime type, enforce separate invariants, or prevent values with the aliased type from being used wherever the original type is accepted.

sealed class

A closed subtype hierarchy

A sealed class restricts which classes may directly inherit from it. Since the compiler knows the permitted cases, a when expression can be checked for exhaustiveness. Sealed hierarchies suit systems where the set of data variants is relatively stable but operations on those variants change. Adding a new variant requires reviewing operations that branch over the hierarchy.

Either

A value holding one of two cases

Either is a generic type that contains a value of one of two possible types, but never both. In the error-handling convention described in the book, the Right case carries a successful result and the Left case carries an error. Mapping functions can transform successes while leaving failures unchanged, allowing errors to be represented in return values rather than thrown as exceptions.

About the Author

Duncan McGregor is an experienced software developer and author known for his expertise in Java and Kotlin programming languages. He co-authored Java to Kotlin, a highly-rated book that guides Java developers in transitioning to Kotlin. McGregor's writing style is praised for its clarity and pragmatic approach, demonstrating a deep understanding of both languages and their practical applications. His work emphasizes the importance of understanding language design principles and best practices in software development. McGregor's insights into the history and evolution of Java and Kotlin provide readers with valuable context for understanding the differences between the two languages and how to effectively leverage Kotlin's features in real-world scenarios.

Download PDF

To save this Java to Kotlin summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.31 MB     Pages: 18

Download EPUB

To read this Java to Kotlin summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.32 MB     Pages: 21
Want to read the full book?
Follow
Listen
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...