Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-13

AuthorSebastian Aigner, Roman Elizarov, Svetlana Isakova, Dmitry Jemerov

From the Front matter: The second edition of Kotlin in Action teaches you the Kotlin programming language and how to use it to build applications running on the Java virtual machine (JVM) and Android. It starts with the basic features of the language and proceeds to cover the more distinctive aspects of Kotlin, such as its support for building high-level abstractions and domain-specific languages. The book also provides the information you need to integrate Kotlin with existing Java projects and helps you introduce Kotlin into your current working environment. The book covers Kotlin 2.0. Who should read this book Kotlin in Action, Second Edition, is primarily focused on developers with some level of Java experience. Kotlin builds on many concepts and techniques from Java, and the book strives to get you up to speed quickly by using your existing knowledge. If you’re experienced with other programming languages such as C# or JavaScript, you may need to refer to other sources of information to understand the more intricate aspects of Kotlin’s interaction with the JVM, but you’ll still be able to learn Kotlin using this book. We focus on the Kotlin language as a whole and not on a specific problem domain, so the book should be equally useful for server-side developers, Android developers, and everyone else who builds projects targeting the JVM.

Tags
No tags
Publisher: Manning Publications
Publish Year: 2024
Language: 英文
File Format: PDF
File Size: 9.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Praise for the first edition “Like all the other great in Action titles from Manning, this book gives you everything you need to become productive quickly.” —Kevin Orr, Sumus Solutions “Kotlin is fun and easy to learn when you have this book to guide you!” —Filip Pravica, Info.nl “Thorough, well written, and easily accessible.” —Jason Lee, NetSuite “Complete introduction guide on the concepts and the paradigms of the Kotlin programming language.” —Ronald Tischliar, system architect, WWK Insurance “Kotlin is an exciting yet pragmatic language that every Java programmer should learn, and this is the only book they’ll need to learn Kotlin well.” —Tim Lavers, senior software engineer, Pacific Knowledge Systems “With deep knowledge shown by the authors, it’s clear they can convey that material to readers.” —Dylan Scott, software developer, Shred Code “A perfect and unique book to start learning the Kotlin language, written by two awesome developers from the Kotlin team in JetBrains.” —Paweł Gajda, Android developer, EL Passion
Kotlin in Action Second Edition Sebastian Aigner, Roman Elizarov, Svetlana Isakova, Dmitry Jemerov To comment go to liveBook
Manning Shelter Island For more information on this and other Manning titles go to www.manning.com
Copyright For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2024 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. ♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and
we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20 Baldwin Road Technical PO Box 761 Shelter Island, NY 11964 Development editor: Marina Michaels Technical development editor: Robert Wenner Review editors: Aleksandar Dragosavljević and Radmila Ercegovac Production editor: Keri Hales Copy editor: Christian Berk Proofreader: Katie Tennant Technical proofreader: Igor Wojda Typesetter: Gordan Salinović
Cover designer: Marija Tudor ISBN: 9781617299605
contents Front matter preface acknowledgments about this book about the authors about the cover illustration Part 1 Introducing Kotlin 1 Kotlin: What and why 1.1 A taste of Kotlin 1.2 Kotlin’s primary traits Kotlin use cases: Android, server side, anywhere Java runs, and beyond Static typing makes Kotlin performant, reliable, and maintainable Combining functional and object-oriented programming makes Kotlin safe and flexible Concurrent and asynchronous code becomes natural and structured with coroutines Kotlin can be used for any purpose: It’s free, open source, and open to contributions 1.3 Areas in which Kotlin is often used Powering backends: Server-side development with Kotlin
Mobile Development: Android is Kotlin first Multiplatform: Sharing business logic and minimizing duplicate work on iOS, JVM, JS, and beyond 1.4 The philosophy of Kotlin Kotlin is a pragmatic language Kotlin is concise Kotlin is safe Kotlin is interoperable 1.5 Using the Kotlin tools Setting up and running the Kotlin code Compiling Kotlin code 2 Kotlin basics 2.1 Basic elements: Functions and variables Writing your first Kotlin program: “Hello, world!” Declaring functions with parameters and return values Making function definitions more concise by using expression bodies Declaring variables to store data Marking a variable as read only or reassignable Easier string formatting: String templates 2.2 Encapsulating behavior and data: Classes and properties
Associating data with a class and making it accessible: Properties Computing properties instead of storing their values: Custom accessors Kotlin source code layout: Directories and packages 2.3 Representing and handling choices: Enums and when Declaring enum classes and enum constants Using the when expression to deal with enum classes Capturing the subject of a when expression in a variable Using the when expression with arbitrary objects Using the when expression without an argument Smart casts: Combining type checks and casts Refactoring: Replacing an if with a when expression Blocks as branches of if and when 2.4 Iterating over things: while and for loops Repeating code while a condition is true: The while loop Iterating over numbers: Ranges and progressions Iterating over maps Using in to check collection and range membership 2.5 Throwing and catching exceptions in Kotlin Handling exceptions and recovering from errors: try, catch, and finally Using try as an expression 3 Defining and calling functions
3.1 Creating collections in Kotlin 3.2 Making functions easier to call Named arguments Default parameter values Getting rid of static utility classes: Top-level functions and properties 3.3 Adding methods to other people’s classes: Extension functions and properties Imports and extension functions Calling extension functions from Java Utility functions as extensions No overriding for extension functions Extension properties 3.4 Working with collections: varargs, infix calls, and library support Extending the Java collections API Varargs: Functions that accept an arbitrary number of arguments Working with pairs: Infix calls and destructuring declarations 3.5 Working with strings and regular expressions Splitting strings Regular expressions and triple-quoted strings Multiline triple-quoted strings 3.6 Making your code tidy: Local functions and extensions
4 Classes, objects, and interfaces 4.1 Defining class hierarchies Interfaces in Kotlin Open, final, and abstract modifiers: Final by default Visibility modifiers: Public by default Inner and nested classes: Nested by default Sealed classes: Defining restricted class hierarchies 4.2 Declaring a class with nontrivial constructors or properties Initializing classes: Primary constructor and initializer blocks Secondary constructors: Initializing the superclass in different ways Implementing properties declared in interfaces Accessing a backing field from a getter or setter Changing accessor visibility 4.3 Compiler-generated methods: Data classes and class delegation Universal object methods Data classes: Autogenerated implementations of universal methods Class delegation: Using the by keyword 4.4 The object keyword: Declaring a class and creating an instance, combined Object declarations: Singletons made easy Companion objects: A place for factory methods and static members Companion objects as regular objects
Object expressions: Anonymous inner classes rephrased 4.5 Extra type safety without overhead: Inline classes 5 Programming with lambdas 5.1 Lambda expressions and member references Introduction to lambdas: Blocks of code as values Lambdas and collections Syntax for lambda expressions Accessing variables in scope Member references Bound callable references 5.2 Using Java functional interfaces: Single abstract methods Passing a lambda as a parameter to a Java method SAM constructors: Explicit conversion of lambdas to functional interfaces 5.3 Defining SAM interfaces in Kotlin: fun interfaces 5.4 Lambdas with receivers: with, apply, and also Performing multiple operations on the same object: with Initializing and configuring objects: The apply function Performing additional actions with an object: also 6 Working with collections and sequences 6.1 Functional APIs for collections Removing and transforming elements: filter and map
Accumulating values for collections: reduce and fold Applying a predicate to a collection: all, any, none, count, and find Splitting a list into a pair of lists: partition Converting a list to a map of groups: groupBy Transforming collections into maps: associate, associateWith, and associateBy Replacing elements in mutable collections: replaceAll and fill Handling special cases for collections: ifEmpty Splitting collections: chunked and windowed Merging collections: zip Processing elements in nested collections: flatMap and flatten 6.2 Lazy collection operations: Sequences Executing sequence operations: Intermediate and terminal operations Creating sequences 7 Working with nullable values 7.1 Avoiding NullPointerExceptions and handling the absence of values: Nullability 7.2 Making possibly null variables explicit with nullable types 7.3 Taking a closer look at the meaning of types 7.4 Combining null checks and method calls with the safe call operator: ?. 7.5 Providing default values in null cases with the Elvis operator: ?: 7.6 Safely casting values without throwing exceptions: as?
7.7 Making promises to the compiler with the non-null assertion operator: !! 7.8 Dealing with nullable expressions: The let function 7.9 Non-null types without immediate initialization: Late-initialized properties 7.10 Extending types without the safe-call operator: Extensions for nullable types 7.11 Nullability of type parameters 7.12 Nullability and Java Platform types Inheritance 8 Basic types, collections, and arrays 8.1 Primitive and other basic types Representing integers, floating-point numbers, characters, and Booleans with primitive types Using the full bit range to represent positive numbers: Unsigned number types Nullable primitive types: Int?, Boolean?, and more Kotlin makes number conversions explicit Any and Any?: The root of the Kotlin type hierarchy The Unit type: Kotlin’s void The Nothing type: “This function never returns” 8.2 Collections and arrays Collections of nullable values and nullable collections Read-only and mutable collections
Kotlin collections and Java collections are deeply related Collections declared in Java are seen as platform types in Kotlin Creating arrays of objects and primitive types for interoperability and performance reasons Part 2 Embracing Kotlin 9 Operator overloading and other conventions 9.1 Overloading arithmetic operators makes operations for arbitrary classes more convenient Plus, times, divide, and more: Overloading binary arithmetic operations Applying an operation and immediately assigning its value: Overloading compound assignment operators Operators with only one operand: Overloading unary operators 9.2 Overloading comparison operators makes it easy to check relationships between objects Equality operators: equals (==) Ordering operators: compareTo (<, >, ⇐, and >=) 9.3 Conventions used for collections and ranges Accessing elements by index: The get and set conventions Checking whether an object belongs to a collection: The in convention Creating ranges from objects: The rangeTo and rangeUntil conventions Making it possible to loop over your types: The iterator convention 9.4 Making destructuring declarations possible with component functions Destructuring declarations and loops
Ignoring destructured values using the _ character 9.5 Reusing property accessor logic: Delegated properties Basic syntax and inner workings of delegated properties Using delegated properties: Lazy initialization and by lazy() Implementing your own delegated properties Delegated properties are translated to hidden properties with custom accessors Accessing dynamic attributes by delegating to maps How a real-life framework might use delegated properties 10 Higher-order functions: Lambdas as parameters and return values 10.1 Declaring functions that return or receive other functions: Higher-order functions Function types specify the parameter types and return values of a lambda Calling functions passed as arguments Java lambdas are automatically converted to Kotlin function types Parameters with function types can provide defaults or be nullable Returning functions from functions Making code more reusable by reducing duplication with lambdas 10.2 Removing the overhead of lambdas with inline functions Inlining means substituting a function body to each call site Restrictions on inline functions Inlining collection operations
Deciding when to declare functions as inline Using inlined lambdas for resource management with withLock, use, and useLines 10.3 Returning from lambdas: Control flow in higher-order functions Return statements in lambdas: returning from an enclosing function Returning from lambdas: Return with a label Anonymous functions: Local returns by default 11 Generics 11.1 Creating types with type arguments: Generic type parameters Functions and properties that work with generic types Generic classes are declared with the angle bracket syntax Restricting the type a generic class or function can use: Type parameter constraints Excluding nullable type arguments by explicitly marking type parameters as non-null 11.2 Generics at run time: Erased and reified type parameters Limitations to finding type information of a generic class at run time: Type checks and casts Functions with reified type parameters can refer to actual type arguments at run time Avoiding java.lang.Class parameters by replacing class references with reified type parameters Declaring accessors with reified type parameters Reified type parameters come with restrictions
11.3 Variance describes the subtyping relationship between generic arguments Variance determines whether it is safe to pass an argument to a function Understanding the differences between classes, types, and subtypes Covariance preserves the subtyping relation Contravariance reverses the subtyping relation Specifying variance for type occurrences via use-site variance Star projection: Using the * character to indicate a lack of information about a generic argument Type aliases 12 Annotations and reflection 12.1 Declaring and applying annotations Applying annotations to mark declarations Specifying the exact declaration an annotation refers to: Annotation targets Using annotations to customize JSON serialization Creating your own annotation declarations Meta-annotations: Controlling how an annotation is processed Passing classes as annotation parameters to further control behavior Generic classes as annotation parameters 12.2 Reflection: Introspecting Kotlin objects at run time The Kotlin reflection API: KClass, KCallable, KFunction, and KProperty Implementing object serialization using reflection
Customizing serialization with annotations JSON parsing and object deserialization The final step of deserialization: callBy() and creating objects using reflection 13 DSL construction 13.1 From APIs to DSLs: Creating expressive custom code structures Domain-specific languages Internal DSLs are seamlessly integrated into the rest of your program The structure of DSLs Building HTML with an internal DSL 13.2 Building structured APIs: Lambdas with receivers in DSLs Lambdas with receivers and extension function types Using lambdas with receivers in HTML builders Kotlin builders: Enabling abstraction and reuse 13.3 More flexible block nesting with the invoke convention The invoke convention: Objects callable as functions The invoke convention in DSLs: Declaring dependencies in Gradle 13.4 Kotlin DSLs in practice Chaining infix calls: The should function in test frameworks Defining extensions on primitive types: Handling dates Member extension functions: Internal DSL for SQL Part 3 Concurrent programming with coroutines and flows