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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Review Summary
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.
People Also Read
Glossary
the grain of a programming language
Its natural design tendenciesThe 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 computationA 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 effectAn 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 breakThis 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 methodAn 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 pipelineA 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 nameA 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 hierarchyA 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 casesEither 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.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.