logo资料库

Kotlin Programming The Big Nerd Ranch Guide.pdf

第1页 / 共477页
第2页 / 共477页
第3页 / 共477页
第4页 / 共477页
第5页 / 共477页
第6页 / 共477页
第7页 / 共477页
第8页 / 共477页
资料共477页,剩余部分请下载后查看
Title Page
Dedication
Acknowledgments
Table of Contents
Introducing Kotlin
Why Kotlin?
Who Is This Book For?
How to Use This Book
For the More Curious
Challenges
Typographical conventions
Using an eBook
Looking Forward
1. Your First Kotlin Application
Installing IntelliJ IDEA
Your First Kotlin Project
Creating your first Kotlin file
Running your Kotlin file
Compilation and execution of Kotlin/JVM code
The Kotlin REPL
For the More Curious: Why Use IntelliJ?
For the More Curious: Targeting the JVM
Challenge: REPL Arithmetic
2. Variables, Constants, and Types
Types
Declaring a Variable
Kotlin’s Built-In Types
Read-Only Variables
Type Inference
Compile-Time Constants
Inspecting Kotlin Bytecode
For the More Curious: Java Primitive Types in Kotlin
Challenge: hasSteed
Challenge: The Unicorn’s Horn
Challenge: Magic Mirror
3. Conditionals
if/else Statements
Adding more conditions
Nested if/else statements
More elegant conditionals
Logical operators
Conditional expressions
Removing braces from if/else expressions
Ranges
when Expressions
String Templates
Challenge: Trying Out Some Ranges
Challenge: Enhancing the Aura
Challenge: Configurable Status Format
4. Functions
Extracting Code to Functions
Anatomy of a Function
Function header
Visibility modifier
Function name declaration
Function parameters
Function return type
Function body
Function scope
Calling a Function
Refactoring to Functions
Writing Your Own Functions
Default Arguments
Single-Expression Functions
Unit Functions
Named Function Arguments
For the More Curious: The Nothing Type
For the More Curious: File-Level Functions in Java
For the More Curious: Function Overloading
For the More Curious: Function Names in Backticks
Challenge: Single-Expression Functions
Challenge: Fireball Inebriation Level
Challenge: Inebriation Status
5. Anonymous Functions and the Function Type
Anonymous Functions
The function type
Implicit returns
Function arguments
The it keyword
Accepting multiple arguments
Type Inference Support
Defining a Function That Accepts a Function
Shorthand syntax
Function Inlining
Function References
Function Type as Return Type
For the More Curious: Kotlin’s Lambdas Are Closures
For the More Curious: Lambdas vs Anonymous Inner Classes
6. Null Safety and Exceptions
Nullability
Kotlin’s Explicit Null Type
Compile Time vs Runtime
Null Safety
Option one: the safe call operator
Using safe calls with let
Option two: the double-bang operator
Option three: checking whether a value is null with if
The null coalescing operator
Exceptions
Throwing an exception
Custom exceptions
Handling exceptions
Preconditions
Null: What Is It Good For?
For the More Curious: Checked vs Unchecked Exceptions
For the More Curious: How Is Nullability Enforced?
7. Strings
Extracting Substrings
substring
split
String Manipulation
Strings are immutable
String Comparison
For the More Curious: Unicode
For the More Curious: Traversing a String’s Characters
Challenge: Improving DragonSpeak
8. Numbers
Numeric Types
Integers
Decimal Numbers
Converting a String to a Numeric Type
Converting an Int to a Double
Formatting a Double
Converting a Double to an Int
For the More Curious: Bit Manipulation
Challenge: Remaining Pints
Challenge: Handling a Negative Balance
Challenge: Dragoncoin
9. Standard Functions
apply
let
run
with
also
takeIf
takeUnless
Using Standard Library Functions
10. Lists and Sets
Lists
Accessing a list’s elements
Index boundaries and safe index access
Checking the contents of a list
Changing a list’s contents
Iteration
Reading a File into a List
Destructuring
Sets
Creating a set
Adding elements to a set
while Loops
The break Expression
Collection Conversion
For the More Curious: Array Types
For the More Curious: Read-Only vs Immutable
Challenge: Formatted Tavern Menu
Challenge: Advanced Formatted Tavern Menu
11. Maps
Creating a Map
Accessing Map Values
Adding Entries to a Map
Modifying Map Values
Challenge: Tavern Bouncer
12. Defining Classes
Defining a Class
Constructing Instances
Class Functions
Visibility and Encapsulation
Class Properties
Property getters and setters
Property visibility
Computed properties
Refactoring NyetHack
Using Packages
For the More Curious: A Closer Look at var and val Properties
For the More Curious: Guarding Against Race Conditions
For the More Curious: Package Private
13. Initialization
Constructors
Primary constructors
Defining properties in a primary constructor
Secondary constructors
Default arguments
Named arguments
Initializer Blocks
Property Initialization
Initialization Order
Delaying Initialization
Late initialization
Lazy initialization
For the More Curious: Initialization Gotchas
Challenge: The Riddle of Excalibur
14. Inheritance
Defining the Room Class
Creating a Subclass
Type Checking
The Kotlin Type Hierarchy
Type casting
Smart casting
For the More Curious: Any
15. Objects
The object Keyword
Object declarations
Object expressions
Companion objects
Nested Classes
Data Classes
toString
equals
copy
Destructuring declarations
Enumerated Classes
Operator Overloading
Exploring the World of NyetHack
For the More Curious: Defining Structural Comparison
For the More Curious: Algebraic Data Types
Challenge: “Quit” Command
Challenge: Implementing a World Map
Challenge: Ring the Bell
16. Interfaces and Abstract Classes
Defining an Interface
Implementing an Interface
Default Implementations
Abstract Classes
Combat in NyetHack
17. Generics
Defining Generic Types
Generic Functions
Multiple Generic Type Parameters
Generic Constraints
vararg and get
in and out
For the More Curious: The reified Keyword
18. Extensions
Defining Extension Functions
Defining an extension on a superclass
Generic Extension Functions
Extension Properties
Extensions on Nullable Types
Extensions, Under the Hood
Extracting to Extensions
Defining an Extensions File
Renaming an Extension
Extensions in the Kotlin Standard Library
For the More Curious: Function Literals with Receivers
Challenge: toDragonSpeak Extension
Challenge: Frame Extension
19. Functional Programming Basics
Function Categories
Transforms
Filters
Combines
Why Functional Programming?
Sequences
For the More Curious: Profiling
For the More Curious: Arrow.kt
Challenge: Reversing the Values in a Map
Challenge: Applying Functional Programming to Tavern.kt
Challenge: Sliding Window
20. Java Interoperability
Interoperating with a Java Class
Interoperability and Nullity
Type Mapping
Getters, Setters, and Interoperability
Beyond Classes
Exceptions and Interoperability
Function Types in Java
21. Building Your First Android Application with Kotlin
Android Studio
Gradle configuration
Project organization
Defining a UI
Running the App on an Emulator
Generating a Character
The Activity Class
Wiring Up Views
Kotlin Android Extensions Synthetic Properties
Setting a Click Listener
Saved Instance State
Reading from the saved instance state
Refactoring to an Extension
For the More Curious: Android KTX and Anko Libraries
22. Introduction to Coroutines
Parsing Character Data
Fetching Live Data
The Android Main Thread
Enabling Coroutines
Specifying a Coroutine with async
launch vs async/await
Suspending Functions
Challenge: Live Data
Challenge: Minimum Strength
23. Afterword
Where to Go from Here
Shameless Plugs
Thank You
A. More Challenges
Leveling Up with Exercism
Glossary
Index
Kotlin Programming: The Big Nerd Ranch Guide by Josh Skeen and David Greenhalgh Copyright © 2018 Big Nerd Ranch, LLC All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, contact Big Nerd Ranch, LLC 200 Arizona Ave NE Atlanta, GA 30307 (770) 817-6373 http://www.bignerdranch.com/ book-comments@bignerdranch.com The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, LLC. Exclusive worldwide distribution of the English edition of this book by Pearson Technology Group 800 East 96th Street Indianapolis, IN 46240 USA http://www.informit.com The authors and publisher have taken care in writing and printing this book but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. ISBN-10 013516236X ISBN-13 978-0135162361 First edition, first printing, July 2018 Release E.1.1.1 2
3
Dedication For Baker, the best little bug. To Rebecca, a driven, patient, beautiful woman, and the reason that this book came to be. To Mom and Dad, for valuing education above all else. — J.S. — D.G. 4
Acknowledgments We received a lot of help in writing this book. Without that help, this book would not be what it is, and it may never even have happened. Thanks are due. First, we need to say thank you to our colleagues at Big Nerd Ranch. Thank you to Stacy Henry and Aaron Hillegass for providing us with the time and space to write this book. It has been immensely gratifying to learn and teach Kotlin. We hope that this book lives up to the trust and the support that we have received. Particular thanks are also due to our colleagues at Big Nerd Ranch. Your careful teaching revealed many bugs in the text, and your thoughtful recommendations led to many improvements in our approach. It is truly wonderful to have colleagues such as you. Thank you Kristin Marsicano, Bolot Kerimbaev, Brian Gardner, Chris Stewart, Paul Turner, Chris Hare, Mark Allison, Andrew Lunsford, Rafael Moreno Cesar, Eric Maxwell, Andrew Bailey, Jeremy Sherman, Christian Keur, Mikey Ward, Steve Sparks, Mark Dalrymple, CBQ, and everyone else at the Ranch who helped us with this work. Our colleagues in operations, marketing, and sales are also instrumental. Classes would literally never be scheduled without their work. Thank you Heather Sharpe, Mat Jackson, Rodrigo "Ram Rod" Perez-Velasco, Nicholas Stolte, Justin Williams, Dan Barker, Israel Machovec, Emily Herman, Patrick Freeman, Ian Eze, and Nikki Porter. We cannot do what we do without what you do. Special thanks and an extra bit of karma are also owed to our amazing students who were adventurous enough to join us for the early access version of the course and were kind enough to help us identify errata. Without your feedback and insights into how to improve the course, this text would not be where it is today. Those students include: Santosh Katta, Abdul Hannan, Chandra Mohan, Benjamin DiGregorio, Peng Wan, Kapil Bhalla, Girish Hanchinal, Hashan Godakanda, Mithun Mahadevan, Brittany Berlanga, Natalie Ryan, Balarka Velidi, Pranay Airan, Jacob Rogers, Jean-Luc Delpech, Dennis Lin, Kristina Thai, Reid Baker, Setareh Lotfi, Harish Ravichandran, Matthew Knapp, Nathan Klee, Brian Lee, Heidi Muth, Martin Davidsson, Misha Burshteyn, Kyle Summers, Cameron Hill, Vidhi Shah, Fabrice Di Meglio, Jared Burrows, Riley Brewer, Michael Krause, Tyler Holland, Gajendra Singh, Pedro Sanchez, Joe Cyboski, Zach Waldowski, Noe Arzate, Allan Caine, Zack Simon, Josh Meyers, Rick Meyers, Stephanie Guevara, Abdulrahman Alshmrani, Robert Edwards, Maribel Montejano, and Mohammad Yusuf. We want to extend a special thank you to our colleagues and members of the Android community who helped us test the book's accuracy, clarity, and ease of use. Without your external perspective, putting this book together would have been even more daunting. Thank you Jon Reeve, Bill Phillips, Matthew Compton, Vishnu Rajeevan, Scott Stanlick, Alex Lumans, Shauvik Choudhary, and Jason Atwood. We also need to acknowledge the many talented folks who worked on the book with us. Elizabeth Holaday, our editor, helped refine the book, crystallize its strengths, and diminish its weaknesses. Anna Bentley, our copyeditor, found and corrected errors and ultimately made us look smarter than we are. Ellie Volckhausen designed the cover. And Chris Loper designed and produced the print book and the EPUB and Kindle versions. Finally, thank you to all our students. Being your teacher offers us the opportunity to be a student in many ways, and for that we are immensely grateful. Teaching is part of the greatest 5
thing that we do, and it has been a pleasure working with you. We hope that the quality of this book matches your enthusiasm and determination. 6
Table of Contents Introducing Kotlin Why Kotlin? Who Is This Book For? How to Use This Book For the More Curious Challenges Typographical conventions Using an eBook Looking Forward 1. Your First Kotlin Application Installing IntelliJ IDEA Your First Kotlin Project Creating your first Kotlin file Running your Kotlin file The Kotlin REPL For the More Curious: Why Use IntelliJ? For the More Curious: Targeting the JVM Challenge: REPL Arithmetic 2. Variables, Constants, and Types Types Declaring a Variable Kotlin’s Built-In Types Read-Only Variables Type Inference Compile-Time Constants Inspecting Kotlin Bytecode For the More Curious: Java Primitive Types in Kotlin Challenge: hasSteed Challenge: The Unicorn’s Horn Challenge: Magic Mirror 3. Conditionals if/else Statements Adding more conditions Nested if/else statements More elegant conditionals Ranges when Expressions String Templates Challenge: Trying Out Some Ranges Challenge: Enhancing the Aura Challenge: Configurable Status Format 4. Functions Extracting Code to Functions Anatomy of a Function Function header Function body 7
Function scope Calling a Function Refactoring to Functions Writing Your Own Functions Default Arguments Single-Expression Functions Unit Functions Named Function Arguments For the More Curious: The Nothing Type For the More Curious: File-Level Functions in Java For the More Curious: Function Overloading For the More Curious: Function Names in Backticks Challenge: Single-Expression Functions Challenge: Fireball Inebriation Level Challenge: Inebriation Status 5. Anonymous Functions and the Function Type Anonymous Functions The function type Implicit returns Function arguments The it keyword Accepting multiple arguments Type Inference Support Defining a Function That Accepts a Function Shorthand syntax Function Inlining Function References Function Type as Return Type For the More Curious: Kotlin’s Lambdas Are Closures For the More Curious: Lambdas vs Anonymous Inner Classes 6. Null Safety and Exceptions Nullability Kotlin’s Explicit Null Type Compile Time vs Runtime Null Safety Exceptions Throwing an exception Custom exceptions Handling exceptions 7. Strings Extracting Substrings substring split Option one: the safe call operator Option two: the double-bang operator Option three: checking whether a value is null with if Preconditions Null: What Is It Good For? For the More Curious: Checked vs Unchecked Exceptions For the More Curious: How Is Nullability Enforced? 8
分享到:
收藏