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
Kotlin in Action

Kotlin in Action

Make Java projects safer and leaner with Kotlin, while keeping your existing tools and libraries.
by Dmitry Jemerov 2016 360 pages
4.41
500+ ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Adopt Kotlin incrementally: gain safety and terseness without abandoning Java

The ecosystem stays familiar. Kotlin runs on the Java platform and interoperates with Java libraries, classes, and tools. A team can convert one class at a time, mix Kotlin and Java in one project, and keep using established frameworks. The book presents Kotlin as useful for server applications and Android, with Java-level performance and a compact runtime. Its compiler also supports type inference, so much of static typing's ceremony can be omitted without giving up compile-time checks.

Start with a small experiment. The book points readers to an interactive console and online playground, and describes an automated Java-to-Kotlin converter. The converted result may need polishing, but it can help developers learn the syntax or begin a gradual migration without requiring a rewrite.

Analysis

Kotlin's strongest adoption strategy is architectural, not merely syntactic: it lets teams change the language of new work while preserving existing investments. That lowers the organizational risk of experimentation, a factor often more decisive than a language's feature list. Interoperability is not magic, however. Mixed-language systems still require clear ownership of APIs and attention to nullability at Java boundaries. The language reduces migration friction, but thoughtful module design is what keeps that flexibility from becoming a permanently tangled codebase.

Make nullable values explicit so the compiler catches unsafe assumptions early

Null is part of the type. In Kotlin, `String` means a value that cannot be null, while `String?` may be null. A direct method call on a nullable value is rejected until the code handles that possibility. The safe-call operator `?.` skips access when the receiver is null, and the Elvis operator `?:` supplies a fallback, returns, or throws an exception. A forceful `!!` assertion is available, but it can still fail at runtime.

Java remains an escape hatch. Java types without nullability annotations arrive as platform types: Kotlin cannot tell whether they permit null, so the developer must decide how to use them. A Kotlin API can be carefully checked while an unannotated Java result still carries uncertainty.

Analysis

This design moves a common class of defects from runtime discovery into the type-checking stage, where failures are cheaper to diagnose. It also makes uncertainty visible in signatures, much as explicit error types do in other languages. The boundary matters: a type system can verify only the information it receives. Platform types preserve convenient Java interop, but they transfer judgment to the caller. Null safety is therefore strongest when teams annotate Java APIs and treat external data as untrusted until checked.

Write declarations around intent, not Java's ceremony

Let common patterns disappear. Kotlin's `val` declares a reference that cannot be reassigned, while `var` permits reassignment. The compiler often infers types from initial values, and `if` and `when` can return values, letting a function express a decision directly. A small data holder can declare constructor properties in its class header instead of repeating fields, assignments, getters, and setters.

Make calls explain themselves. Named arguments clarify calls with several parameters, and default values reduce the need for overloaded functions. Top-level functions avoid utility-only classes. Properties provide getter-like access in Kotlin, while custom accessors can calculate values when needed. These features are intended to remove code that merely repeats language conventions, not to compress source into cryptic shorthand.

Analysis

The useful measure of concision is not character count but how quickly a reader can reconstruct intent. Named parameters and properties act like lightweight documentation embedded in the call site, while immutable references make reassignment less likely to hide in a long function. Yet terseness can become opacity when a team leans too heavily on inference or clever expression chains. A good rule is to let the compiler infer routine facts, but spell out types and intermediate steps when they carry important domain meaning.

Pass behavior as values to eliminate duplicated loops and policies

Separate the pattern from the choice. A higher-order function accepts another function or returns one. In collection code, `filter`, `map`, and `maxBy` let a library hold the recurring traversal while a lambda states the task-specific rule. The book's website-visit example starts by calculating average visit duration for one operating system, then generalizes the function to accept a predicate. That makes queries such as mobile users or visitors to a particular page variations of one reusable operation.

Lambdas can capture state. A lambda may use variables from its surrounding function, including mutable ones. That is convenient for local counting, but asynchronous callbacks can run after the function returns, so changing a local variable there does not make its eventual value available to the caller.

Analysis

This is a practical form of abstraction: instead of inventing a new class for every policy, the program passes the policy as data. It resembles the Strategy pattern, but with less scaffolding, and it encourages libraries to expose general operations that callers can customize. The tradeoff is that behavior becomes less visible in a call graph. Captured mutable state also deserves scrutiny, especially across threads or delayed callbacks, where a compact lambda can conceal lifetime and synchronization issues.

Use sequences for large pipelines, not as a reflex

Collections work eagerly. Chaining collection operations such as mapping names and filtering them creates intermediate collections. For a small list, this is usually clear and efficient, especially because many Kotlin collection functions are inline and avoid extra lambda objects.

Sequences defer work. Converting a collection with `asSequence()` makes intermediate operations lazy. Each element passes through the chain in turn, and a terminal operation such as `toList()`, `sum()`, or `find()` triggers the work. A search can stop as soon as it finds a match, so later elements need not be transformed. Filter order matters too: filtering before mapping can avoid transformations for elements that will be discarded. Sequences help when large pipelines make intermediate collections costly, but they add their own machinery.

Analysis

The distinction is a useful reminder that elegant syntax does not determine execution cost. Lazy evaluation can reduce allocation and short-circuit work, while eager evaluation can be simpler and may benefit from inlining. This is the same tradeoff seen in database query plans and streaming systems: defer work when it avoids meaningful waste, not merely because laziness sounds sophisticated. Performance should be measured against realistic data sizes, since a pipeline optimized for millions of records may only obscure a tiny operation.

Keep classes closed by default and delegate behavior instead of inheriting blindly

Inheritance requires permission. Kotlin classes and members are final by default. A developer must mark a class `open` to allow subclassing, making extensibility an explicit design choice. The book connects this to the fragile base class problem: changes to a superclass can undermine assumptions made by subclasses.

Let the compiler forward routine work. The `by` delegation feature lets a wrapper implement an interface by forwarding its behavior to another object. A counting collection can delegate ordinary operations to an underlying set and override only `add` and `addAll` to record attempts. Data classes address another source of mechanical code by generating value-based equality, hashing, readable string output, and a copy operation from constructor properties.

Analysis

These features point toward composition as the default relationship between components. Restricting inheritance reduces the number of hidden dependencies a base class must support, while delegation allows behavior to be assembled around stable interfaces. Data classes, meanwhile, make value semantics explicit rather than leaving equality to object identity. The caution is that compiler-generated behavior follows the declared structure: a mutable property included in equality can make an object unsafe as a hash-map key. Convenience still depends on choosing the right model.

Turn domain rules into readable, statically checked Kotlin DSLs

Give code a domain grammar. An internal DSL is a structured way to use a general-purpose language for a particular task. Kotlin uses extension functions, infix calls, and lambdas with receivers to make such code read more like the domain. In an HTML builder, a table block can expose row creation, and a row block can expose cell creation. Putting a cell in an invalid context can fail at compile time, while ordinary Kotlin loops can generate rows from data.

Reuse remains available. The book also shows a database query written through Exposed, where chained calls describe selection, grouping, and ordering while the framework generates SQL. Because the DSL is Kotlin code, developers can extract helper functions and share logic rather than copying markup or query strings.

Analysis

A well-designed DSL does more than look pleasant: it constrains the set of valid actions and makes domain structure visible. Receiver lambdas provide a form of contextual guidance, while static types and IDE support help expose mistakes during construction. The design burden shifts to the library author, who must choose a grammar that is readable without becoming a miniature puzzle. A DSL is most valuable when it encodes recurring domain rules, not when it merely hides a straightforward function call.

Treat variance as a promise about how generic values flow

Ask whether a type produces or consumes. Kotlin generics are erased at runtime, so ordinary code cannot inspect a list and prove its element type. Variance controls which generic types can safely substitute for others. A read-only `List<out T>` produces values, so a list of cats can be used where a list of animals is expected. A mutable list both produces and consumes values, so allowing that substitution could let a function insert a non-cat into a cat list. A consumer such as `Comparator<in T>` can accept a broader type safely.

Reification is a narrow exception. An inline function can mark a type parameter `reified`, allowing checks such as filtering a mixed collection to strings. The compiler substitutes the specific type at each call site; ordinary generic functions cannot recover erased type arguments.

Analysis

Variance is best understood as an API contract about information flow, not as punctuation to memorize. Producers can safely become more general because callers only receive values; consumers can safely accept more general inputs because they impose fewer restrictions. This connects type design to capability boundaries: a read-only interface grants fewer powers than a mutable one. Reified parameters are useful, but they do not reverse type erasure throughout the system. Their inline-only nature is a focused tool with code-size and interoperability costs.

Use annotations and reflection to build adaptable tools, then cache the expensive discovery

Let metadata guide generic behavior. An annotation attaches information to a declaration, and reflection inspects classes and properties at runtime. The book demonstrates both in JKid, a small JSON library. It discovers an object's properties and serializes their values, while annotations can rename a JSON key, exclude a property, or select a custom serializer. Deserialization parses JSON, matches keys to constructor parameters, and uses reflection to create an instance, including support for default constructor values.

Pay for discovery once. Reflection must search properties, parameters, and annotations, so JKid caches class information rather than repeating the search for every field. The example shows how a small library can turn metadata into adaptable behavior, while also revealing why reflective code needs careful type checks and useful errors.

Analysis

Reflection makes a library extensible because it can operate on types that were not known when the library was written. Annotations then provide a declarative control surface, separating user intent from the machinery that interprets it. This pattern underlies serializers, dependency injection, and test frameworks. Its cost is reduced compile-time certainty and more responsibility at runtime. Caching metadata is not just an optimization; it also creates a natural place to validate assumptions once and report configuration errors before they become confusing failures.

Analysis

Kotlin in Action is both a language introduction and an argument about language design. Its central claim is practical: a language can make common programming work safer and more expressive without requiring developers to abandon the Java ecosystem. The book supports that claim through a progression from concise declarations and null-aware types to lambdas, generic variance, reflection, and DSL construction. Each feature is presented as a way to move repetition or ambiguity out of application code and into compiler rules or reusable libraries.

The most coherent design pattern is explicit capability. A nullable type announces that null must be handled. A final class announces that inheritance is not part of its contract. A read-only collection type communicates that the current API offers no mutation. Variance then explains when broader or narrower generic values can safely cross a boundary. These are not isolated conveniences. Together they make more assumptions visible in signatures, where tools can reason about them.

The book is equally pragmatic about its limits. Kotlin does not enforce functional purity, and a read-only collection reference is not necessarily an immutable object. Java platform types preserve interoperability by leaving nullability decisions to the developer. Generic type erasure limits runtime inspection, while reflection shifts some validation from compile time to execution. The language reduces risk, but cannot remove the need to understand ownership, mutation, and trust at system boundaries.

Its DSL examples show the most ambitious payoff: library APIs can acquire a grammar while remaining ordinary, statically checked Kotlin. That expressiveness is powerful precisely because the host language remains available for loops, abstraction, and tooling. The corresponding burden is API design. Poorly chosen syntax can turn a DSL into a private dialect that users must decipher.

The book is a 2016-era Kotlin guide, so some tooling and ecosystem details are historically situated. Its durable lesson is broader: successful language adoption depends on aligning readable syntax, enforceable contracts, and compatibility with existing systems.

Summary in 30 Seconds
Kotlin makes nullability part of a type, so the compiler can require checks before nullable values are used. Type inference, properties, default arguments, and lambdas reduce repetitive code while retaining static checks. Sequences can avoid intermediate collections in large pipelines, but eager operations are often simpler for small ones. Final classes make inheritance opt-in, and delegation forwards routine behavior. Variance expresses safe ways for generic values to flow. Reflection enables adaptable tools, while caching avoids repeated metadata searches.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.41 out of 5
Average of 500+ ratings from Goodreads and Amazon.

Kotlin in Action receives mostly positive reviews, with readers praising its comprehensive coverage of Kotlin features, clear explanations, and comparison to Java. Many find it excellent for experienced programmers transitioning from Java to Kotlin. Highlights include the chapters on generics, DSLs, and lambdas. Some readers note the book's density and occasional complexity, especially in later chapters. A few criticize its treatment of Java, while others appreciate the insights into Kotlin's design decisions. Overall, it's highly recommended for those with programming experience looking to learn Kotlin.

Your rating:
4.65
115 ratings
Want to read the full book?

Glossary

nullable type

Type that permits null

A Kotlin type marked with a question mark, such as String?, whose values may be null. The compiler restricts operations on nullable values until code handles the possibility of null, for example with a safe call, a null check, or a fallback. A type without the question mark is non-null by default.

platform type

Java type of unknown nullability

A type coming from Java code for which Kotlin has no reliable nullability information, often because the Java declaration lacks annotations. Kotlin lets a caller treat it as nullable or non-null, preserving convenient interoperability but placing responsibility on the caller to understand the Java API's actual behavior.

smart cast

Compiler-applied checked cast

After a successful type check, Kotlin can treat a value as having the checked type without requiring an explicit cast. For example, after confirming that an expression is a number node, code can access that node's value directly. Smart casts require the compiler to know that the value cannot change between the check and its use.

extension function

External function with receiver syntax

A function declared outside a class but callable with that class's instances using member-like syntax. It can make existing Java or Kotlin APIs more convenient without modifying their source or adding runtime adapter objects. Extensions do not gain access to private or protected members, and dispatch is resolved from the receiver's declared type.

delegated property

Property whose access uses a delegate

A property whose getter and, when mutable, setter forward their work to another object through the by syntax. The delegate supplies convention methods such as getValue and setValue. This allows reusable property behavior, including lazy initialization, change notifications, map-backed values, and framework-managed storage.

declaration-site variance

Variance specified on a type

A Kotlin rule placed on a generic class or interface's type parameter. The out modifier allows the type parameter to appear in output positions and preserves the subtype relationship between type arguments. The in modifier allows input positions and reverses that relationship. The compiler checks these restrictions to protect type safety.

reified type parameter

Type argument available at runtime

A type parameter marked reified on an inline function. Because the compiler inserts the function body at each call site, it can use the actual type argument for operations such as type checks or retrieving a class reference. Reified parameters are unavailable on ordinary non-inline functions because generic type arguments are erased at runtime.

lambda with receiver

Lambda with an implicit context object

A lambda whose function type names a receiver, such as StringBuilder.() -> Unit. When invoked with a StringBuilder instance, the lambda can access that object's members directly, often without repeating a variable name. This feature supports builder-style APIs and helps create structured Kotlin DSLs.

internal DSL

Domain-specific API written in Kotlin

A structured way of using Kotlin to express operations in a particular domain, rather than writing a separate language or embedding its syntax in a string. Extension functions, infix calls, and receiver lambdas can create a domain-like grammar while retaining Kotlin's type checking, IDE support, and ability to reuse ordinary language constructs.

FAQ

What's Kotlin in Action about?

  • Comprehensive Guide: Kotlin in Action is a detailed guide to the Kotlin programming language, covering its features, syntax, and best practices.
  • Three-Part Structure: The book is divided into three parts, focusing on basic syntax, building reusable abstractions, and applying Kotlin in real-world projects.
  • Authoritative Insights: Written by Dmitry Jemerov and Svetlana Isakova, the book provides authoritative information and practical examples to help readers become proficient in Kotlin.

Why should I read Kotlin in Action?

  • Practical Approach: The book emphasizes practical applications of Kotlin, making it suitable for developers looking to implement Kotlin in their projects quickly.
  • Interoperability with Java: It thoroughly covers Kotlin's interoperability with Java, making it an excellent resource for Java developers transitioning to Kotlin.
  • Expert Insights: Written by experienced Kotlin developers, the book offers expert insights and practical advice, enhancing understanding of Kotlin's design decisions.

What are the key takeaways of Kotlin in Action?

  • Kotlin's Features: Readers will learn about Kotlin's concise syntax, null safety, and powerful type system, which help reduce common programming errors.
  • Functional Programming: The book introduces functional programming concepts in Kotlin, such as higher-order functions and lambdas, for more expressive code.
  • Real-World Applications: It provides practical insights into applying Kotlin in various contexts, including Android development and server-side applications.

What are the best quotes from Kotlin in Action and what do they mean?

  • "Kotlin is pragmatic, safe, concise, and interoperable.": This quote summarizes Kotlin's core philosophy, emphasizing its practical applications and seamless integration with Java.
  • "Null safety is one of the key features of Kotlin.": This statement underscores Kotlin's focus on preventing null pointer exceptions, enhancing code reliability.
  • "Kotlin encourages a functional programming style.": This quote highlights Kotlin's support for functional programming, promoting cleaner and more maintainable code.

How does Kotlin in Action explain Kotlin's approach to null safety?

  • Nullable Types: Kotlin distinguishes between nullable and non-nullable types, helping prevent NullPointerExceptions at compile time.
  • Safe Call Operator: The ?. operator allows method calls on nullable types without risking null reference exceptions.
  • Elvis Operator: The ?: operator provides a default value if a nullable expression evaluates to null, leading to cleaner code.

How does Kotlin in Action describe Kotlin's handling of collections?

  • Unified Collection Types: Kotlin does not differentiate between primitive and reference types, allowing for a consistent approach to collections.
  • Extension Functions: Kotlin extends Java's collection classes with functions like filter, map, and flatMap, simplifying operations on collections.
  • Lazy Evaluation with Sequences: Sequences allow for lazy evaluation of collection operations, improving performance by avoiding intermediate collections.

What are lambdas and how are they used in Kotlin according to Kotlin in Action?

  • Definition of Lambdas: Lambdas are anonymous functions that can be passed as parameters, allowing for concise and expressive code.
  • Lambda Syntax: In Kotlin, lambdas are defined using curly braces {} and can access variables from their surrounding scope.
  • Member References: Kotlin allows for member references using the :: operator, providing a shorthand for passing functions.

How does Kotlin in Action explain Kotlin's type system improvements?

  • Explicit Nullability: Kotlin's type system requires explicit declaration of nullability, reducing runtime null reference errors.
  • Smart Casts: The compiler automatically casts types after a type check, allowing for cleaner and safer code.
  • Sealed Classes: Sealed classes restrict class hierarchies, ensuring exhaustive checks in when expressions, enhancing code safety.

What are data classes in Kotlin as explained in Kotlin in Action?

  • Purpose of Data Classes: Data classes are designed to hold data and automatically generate common methods like equals(), hashCode(), and toString().
  • Primary Constructor: A data class must have a primary constructor with at least one parameter, defining the class properties.
  • Copy Method: Data classes provide a copy() method for creating new instances with modified properties, maintaining immutability.

How does Kotlin in Action describe class delegation in Kotlin?

  • Class Delegation: Kotlin allows class delegation using the by keyword, simplifying interface implementation without boilerplate code.
  • Avoiding Boilerplate: Delegation avoids repetitive code for methods that forward calls to another object, leading to cleaner code.
  • Custom Behavior: Specific methods can be overridden to add custom behavior while still delegating the rest of the implementation.

What are companion objects in Kotlin according to Kotlin in Action?

  • Definition of Companion Objects: Companion objects are special objects within a class that hold static-like members and methods.
  • Accessing Companion Members: Members of a companion object can be accessed using the class name, similar to static members in Java.
  • Implementing Interfaces: Companion objects can implement interfaces, allowing for consistent instance creation or operations related to the class.

How does Kotlin in Action explain higher-order functions in Kotlin?

  • Functions as First-Class Citizens: Higher-order functions can take other functions as parameters or return them, allowing for flexible code structures.
  • Lambda Expressions: Kotlin supports lambda expressions, enabling functional programming paradigms within the language.
  • Practical Applications: Higher-order functions are used in collection operations like map, filter, and reduce, allowing for expressive code.

About the Author

Dmitry Jemerov is one of the authors of Kotlin in Action and a key figure in the development of the Kotlin programming language. As a member of the core team at JetBrains, the company behind Kotlin, Jemerov has been instrumental in shaping the language's design and features. His expertise in programming language development and deep understanding of Kotlin's internals are evident in the book's detailed explanations and insights into the language's design decisions. Jemerov's background in Java and his involvement in Kotlin's creation allow him to provide valuable comparisons between the two languages throughout the book.

Download PDF

To save this Kotlin in Action summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.38 MB     Pages: 20

Download EPUB

To read this Kotlin in Action 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.36 MB     Pages: 23
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 25,
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...