Movatterモバイル変換


[0]ホーム

URL:


Skip to Content
Head First Kotlin
book

Head First Kotlin

byDawn Griffiths,David Griffiths
February 2019
Beginner
480 pages
11h 48m
English

Read now

Unlock full access

Contents

  • Who is this book for?Who should probably back away from this book?We know what you’re thinkingWe know what your brain is thinkingMetacognition: thinking about thinkingHere’s what WE did:Here’s what YOU can do to bend your brain into submissionRead meThe technical review teamAcknowledgmentsO’Reilly
  • Welcome to KotlinvilleIt’s crisp, concise and readableYou can use object-oriented AND functional programmingThe compiler keeps you safeYou can use Kotlin nearly everywhereJava Virtual Machines (JVMs)AndroidClient-side and server-side JavaScriptNative appsWhat we’ll do in this chapterInstall IntelliJ IDEA (Community Edition)Let’s build a basic application1. Create a new project2. Specify the type of project3. Configure the projectYou’ve just created your first Kotlin projectAdd a new Kotlin file to the projectAnatomy of the main functionAdd the main function to App.ktTest driveWhat the Run command doesWhat can you say in the main function?Loop and loop and loop...Simple boolean testsA loopy exampleTest driveConditional branchingUsing if to return a valueUpdate the main functionTest driveCode MagnetsUsing the Kotlin interactive shellYou can add multi-line code snippets to the REPLIt’s exercise timeCode Magnets SolutionYour Kotlin Toolbox
  • Your code needs variablesA variable is like a cupWhat happens when you declare a variableThe value is transformed into an object......and the compiler infers the variable’s type from that of the objectThe variable holds a reference to the objectval vs. var revisitedKotlin’s basic typesIntegersFloating pointsBooleansCharacters and StringsHow to explicitly declare a variable’s typeDeclaring the type AND assigning a valueUse the right value for the variable’s typeAssigning a value to another variableWe need to convert the valueAn object has state and behaviorHow to convert a numeric value to another typeWhat happens when you convert a valueWatch out for overspillStore multiple values in an arrayHow to create an arrayCreate the Phrase-O-Matic applicationAdd the code to PhraseOMatic.ktThe compiler infers the array’s type from its valuesHow to explicitly define the array’s typevar means the variable can point to a different arrayval means the variable points to the same array forever......but you can still update the variables in the arrayCode MagnetsCode Magnets SolutionYour Kotlin Toolbox
  • Let’s build a game: Rock, Paper, ScissorsHow the game will workA high-level design of the gameHere’s what we’re going to doGet started: create the projectGet the game to choose an optionCreate the Rock, Paper, Scissors arrayHow you create functionsYou can send things to a functionYou can send more than one thing to a functionCalling a two-parameter function, and sending it two argumentsYou can pass arguments to a function so long as the argument type matches the parameter typeYou can get things back from a functionFunctions with no return valueFunctions with single-expression bodiesCreate the getGameChoice functionCode MagnetsCode Magnets SolutionAdd the getGameChoice function to Game.ktBehind the scenes: what happensThe story continuesThe getUserChoice functionAsk for the user’s choiceHow for loops workLooping through a range of numbersUse downTo to reverse the rangeUse step to skip numbers in the rangeLooping through the items in an arrayAsk the user for their choiceUse the readLine function to read the user’s inputWe need to validate the user’s input‘And’ and ‘Or’ operators (&& and ||)Not equals (!= and !)Use parentheses to make your code clearAdd the getUserChoice function to Game.ktTest driveWe need to print the resultsAdd the printResult function to Game.ktTest driveYour Kotlin Toolbox
  • Object types are defined using classesYou can define your own classesHow to design your own classesLet’s define a Dog classHow to create a Dog objectHow to access properties and functionsWhat if the Dog is in a Dog array?Create a Songs applicationTest driveThe miracle of object creationHow objects are createdWhat the Dog constructor looks likeBehind the scenes: calling the Dog constructorCode MagnetsCode Magnets SolutionGoing deeper into propertiesBehind the scenes of the Dog constructorFlexible property initializationHow to use initializer blocksYou MUST initialize your propertiesHow do you validate property values?The solution: custom getters and settersHow to write a custom getterHow to write a custom setterThe full code for the Dogs projectTest driveYour Kotlin Toolbox
  • Inheritance helps you avoid duplicate codeAn inheritance exampleWhat we’re going to doDesign an animal class inheritance structureUse inheritance to avoid duplicate code in subclassesWhat should the subclasses override?The animals have different property values......and different function implementationsWe can group some of the animalsAdd Canine and Feline classesUse IS-A to test your class hierarchyUse HAS-A to test for other relationshipsThe IS-A test works anywhere in the inheritance treeWe’ll create some Kotlin animalsDeclare the superclass and its properties and functions as openHow a subclass inherits from a superclassHow (and when) to override propertiesOverriding properties lets you do more than assign default valuesHow to override functionsThe rules for overriding functionsAn overridden function or property stays open......until it’s declared finalAdd the Hippo class to the Animals projectCode MagnetsCode Magnets SolutionAdd the Canine and Wolf classesWhich function is called?Inheritance guarantees that all subclasses have the functions and properties defined in the superclassAny place where you can use a superclass, you can use one of its subclasses insteadWhen you call a function on the variable, it’s the object’s version that respondsYou can use a supertype for a function’s parameters and return typeThe updated Animals codeTest driveYour Kotlin Toolbox
  • The Animal class hierarchy revisitedSome classes shouldn’t be instantiatedDeclare a class as abstract to stop it from being instantiatedAbstract or concrete?An abstract class can have abstract properties and functionsWe can mark three properties as abstractThe Animal class has two abstract functionsHow to implement an abstract classYou MUST implement all abstract properties and functionsLet’s update the Animals projectTest driveIndependent classes can have common behaviorAn interface lets you define common behavior OUTSIDE a superclass hierarchyLet’s define the Roamable interfaceInterface functions can be abstract or concreteHow to define interface propertiesDeclare that a class implements an interface......then override its properties and functionsHow to implement multiple interfacesHow do you know whether to make a class, a subclass, an abstract class, or an interface?Update the Animals projectTest driveInterfaces let you use polymorphismAccess uncommon behavior by checking an object’s typeWhere to use the is operatorAs the condition for an ifIn conditions using && and ||In a while loopUse when to compare a variable against a bunch of optionsThe is operator usually performs a smart castUse as to perform an explicit castUpdate the Animals projectTest driveYour Kotlin Toolbox
  • == calls a function named equalsequals is inherited from a superclass named AnyThe importance of being AnyThe common behavior defined by AnyWe might want equals to check whether two objects are equivalentA data class lets you create data objectsHow to create objects from a data classData classes override their inherited behaviorThe equals function compares property valuesEqual objects return the same hashCode valuetoString returns the value of each propertyCopy data objects using the copy functionData classes define componentN functions......that let you destructure data objectsCreate the Recipes projectTest driveGenerated functions only use properties defined in the constructorInitializing many properties can lead to cumbersome codeDefault parameter values to the rescue!How to use a constructor’s default values1. Passing values in order of declaration2. Using named argumentsFunctions can use default values tooOverloading a functionDos and don’ts for function overloading:Let’s update the Recipes projectThe code continued...Test driveYour Kotlin Toolbox
  • How do you remove object references from variables?Remove an object reference using nullWhy have nullable types?You can use a nullable type everywhere you can use a non-nullable typeHow to create an array of nullable typesHow to access a nullable type’s functions and propertiesKeep things safe with safe callsYou can chain safe calls togetherWhat happens when a safe call chain gets evaluatedThe story continuesYou can use safe calls to assign values......and assign values to safe callsUse let to run code if values are not nullUsing let with array itemsUsing let to streamline expressionsInstead of using an if expression......you can use the safer Elvis operatorThe !! operator deliberately throws a NullPointerExceptionCreate the Null Values projectThe code continued...Test driveAn exception is thrown in exceptional circumstancesYou can catch exceptions that are thrownCatch exceptions using a try/catchUse finally for the things you want to do no matter whatAn exception is an object of type ExceptionYou can explicitly throw exceptionstry and throw are both expressionsHow to use try as an expressionHow to use throw as an expressionCode MagnetsCode Magnets SolutionYour Kotlin Toolbox
  • Arrays can be useful......but there are things an array can’t handleYou can’t change an array’s sizeArrays are mutable, so they can be updatedWhen in doubt, go to the LibraryList, Set and MapList - when sequence mattersSet - when uniqueness mattersMap - when finding something by key mattersFantastic Lists......and how to use themCreate a MutableList.....and add values to itYou can remove a value......and replace one value with anotherYou can change the order and make bulk changes......or take a copy of the entire MutableListCreate the Collections projectTest driveCode MagnetsCode Magnets SolutionLists allow duplicate valuesHow to create a SetHow to use a Set’s valuesHow a Set checks for duplicatesHash codes and equalityEquality using the === operatorEquality using the == operatorRules for overriding hashCode and equalsHow to use a MutableSetYou can copy a MutableSetUpdate the Collections projectTest driveTime for a MapHow to create a MapHow to use a MapCreate a MutableMapPut entries in a MutableMapYou can remove entries from a MutableMapYou can copy Maps and MutableMapsThe full code for the Collections projectTest driveYour Kotlin Toolbox
  • Collections use genericsHow a MutableList is definedUnderstanding collection documentation (Or, what’s the meaning of “E”?)Using type parameters with MutableListThings you can do with a generic class or interfaceHere’s what we’re going to doCreate the Pet class hierarchyDefine the Contest classDeclare that Contest uses a generic typeYou can restrict T to a specific supertypeAdd the scores propertyCreate the addScore functionCreate the getWinners functionCreate some Contest objectsThe compiler can infer the generic typeCreate the Generics projectTest driveThe Retailer hierarchyDefine the Retailer interfaceWe can create CatRetailer, DogRetailer and FishRetailer objects......but what about polymorphism?Use out to make a generic type covariantCollections are defined using covariant typesUpdate the Generics projectTest driveWe need a Vet classAssign a Vet to a ContestCreate Vet objectsPass a Vet to the Contest constructorUse in to make a generic type contravariantShould a Vet<Cat> ALWAYS accept a Vet<Pet>?A generic type can be locally contravariantUpdate the Generics projectTest driveYour Kotlin Toolbox
  • Introducing lambdasWhat we’re going to doWhat lambda code looks likeYou can assign a lambda to a variableExecute a lambda’s code by invoking itWhat happens when you invoke a lambdaLambda expressions have a typeThe compiler can infer lambda parameter typesYou can replace a single parameter with itUse the right lambda for the variable’s typeUse Unit to say a lambda has no return valueCreate the Lambdas projectTest driveYou can pass a lambda to a functionAdd a lambda parameter to a function by specifying its name and typeInvoke the lambda in the function bodyCall the function by passing it parameter valuesWhat happens when you call the functionYou can move the lambda OUTSIDE the ()’s......or remove the ()’s entirelyUpdate the Lambdas projectTest driveA function can return a lambdaWrite a function that receives AND returns lambdasDefine the parameters and return typeDefine the function bodyHow to use the combine functionWhat happens when the code runsYou can make lambda code more readableUse typealias to provide a different name for an existing typeUpdate the Lambdas projectTest driveCode MagnetsCode Magnets SolutionYour Kotlin Toolbox
  • Kotlin has a bunch of built-in higher-order functionsThe min and max functions work with basic typesThe minBy and maxBy functions work with ALL typesA closer look at minBy and maxBy’s lambda parameterWhat about minBy and maxBy’s return type?The sumBy and sumByDouble functionssumBy and sumByDouble’s lambda parameterCreate the Groceries projectTest driveMeet the filter functionThere’s a whole FAMILY of filter functionsUse map to apply a transform to your collectionYou can chain function calls togetherWhat happens when the code runsThe story continues...forEach works like a for loopforEach has no return valueLambdas have access to variablesUpdate the Groceries projectTest driveUse groupBy to split your collection into groupsYou can use groupBy in function call chainsHow to use the fold functionBehind the scenes: the fold functionSome more examples of foldFind the product of a List<Int>Concatenate together the name of each item in a List<Grocery>Subtract the total price of items from an initial valueUpdate the Groceries projectTest driveYour Kotlin ToolboxLeaving town...It’s been great having you here in Kotlinville
  • Let’s build a drum machine1. Create a new GRADLE project2. Enter an artifact ID3. Specify configuration details4. Specify the project nameAdd the audio filesAdd the code to the projectTest driveUse coroutines to make beats play in parallel1. Add a coroutines dependency2. Launch a coroutineTest driveA coroutine is like a lightweight threadUse runBlocking to run coroutines in the same scopeTest driveThread.sleep pauses the current THREADThe delay function pauses the current COROUTINEThe full project codeTest drive
  • Kotlin can use existing testing librariesAdd the JUnit libraryCreate a JUnit test classUsing KotlinTestUse rows to test against sets of data
  • 1. Packages and importsHow to add a packagePackage declarationsThe fully qualified nameType the fully qualified name......or import it2. Visibility modifiersVisibility modifiers and top level codeVisibility modifiers and classes/interfaces3. Enum classesEnum constructorsenum properties and functions4. Sealed classesSealed classes to the rescue!How to use sealed classes5. Nested and inner classesAn inner class can access the outer class members6. Object declarations and expressionsClass objects......and companion objectsObject expressions7. Extensions8. Return, break and continueUsing labels with break and continueUsing labels with return9. More fun with functionsvararginfixinline10. InteroperabilityInteroperability with JavaUsing Kotlin with JavaScriptWriting native code with Kotlin

Overview

What will you learn from this book?

Head First Kotlin is a complete introduction to coding in Kotlin. This hands-on book helps you learn the Kotlin language with a unique method that goes beyond syntax and how-to manuals and teaches you how to think like a great Kotlin developer. You’ll learn everything from language fundamentals to collections, generics, lambdas, and higher-order functions. Along the way, you’ll get to play with both object-oriented and functional programming. If you want to really understand Kotlin, this is the book for you.

Why does this book look so different?

Based on the latest research in cognitive science and learning theory,Head First Kotlin uses a visually rich format to engage your mind rather than a text-heavy approach that puts you to sleep. Why waste your time struggling with new concepts? This multisensory learning experience is designed for the way your brain really works.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

You might also like

Programming Kotlin

Programming Kotlin

Venkat Subramaniam
Java to Kotlin

Java to Kotlin

Duncan McGregor, Nat Pryce
Java to Kotlin

Java to Kotlin

Duncan McGregor, Nat Pryce

Publisher Resources

ISBN: 9781491996683Errata Page

[8]ページ先頭

©2009-2026 Movatter.jp