Head first kotlin pdf download






















If you haven't, you're in for a treat. With this book, you'll learn Git through a multisensory experience that engages your mind rather than a text-heavy approach that puts you to sleep.

It offers on expressiveness and safety without compromising simplicity, seamless interoperability with existing Java code, and great tooling support. Because Kotlin generates regular Java bytecode and works together with existing Java libraries and frameworks, it can be used almost everywhere where Java is used today - for server-side development, Android apps, and much more.

Kotlin in Action takes experienced Java developers from the language basics all the way through building applications to run on the JVM and Android devices. Written by core developers of Kotlin, this example-rich book begins by teaching the basic syntax of the Kotlin language. Then readers learn how to use features that let them build reusable abstractions, higher-level functions, libraries, and even entire domain specific languages.

Finally, the book focuses on details of applying Kotlin in real-world projects, such as build system integration, Android support and concurrent programming. With this unique cookbook, developers will learn how to apply thisJava-based language to their own projects. Both experienced programmers and those new to Kotlin will benefit from the practical recipes in this book. Author Ken Kousen Modern Java Recipes shows you how to solve problems with Kotlin by concentrating on your own use cases rather than on basic syntax.

You provide the contextand this book supplies the answers. Already big in Android development, Kotlin can be used anywhere Java is applied, as well as for iOS development, native applications, JavaScriptgeneration, and more. Jump in and build meaningful projects with Kotlin today. Apply functional programming concepts, including lambdas, sequences, and concurrency See how to use delegates, late initialization, and scope functions Explore Java interoperability and access Java libraries using Kotlin Add your own extension functions Use helpful libraries such as JUnit 5 Get practical advice for working with specific frameworks, like Android and Spring.

If you want to see what Kotlin has to offer, this book is ideal for you. What You Will Learn Use new features to write structured and readable object-oriented code Find out how to use lambdas and higher order functions to write clean, reusable, and simple code Write unit tests and integrate Kotlin tests with Java code in a transitioning code base Write real-world production code in Kotlin in the style of microservices Leverage Kotlin's extensions to the Java collections library Use destructuring expressions and find out how to write your own Write code that avoids null pointer errors and see how Java-nullable code can integrate with features in a Kotlin codebase Discover how to write functions in Kotlin, see the new features available, and extend existing libraries Learn to write an algebraic data types and figure out when they should be used In Detail Kotlin has been making waves ever since it was open sourced by JetBrains in ; it has been praised by developers across the world and is already being adopted by companies.

This book provides a detailed introduction to Kotlin that shows you all its features and will enable you to write Kotlin code to production. We start with the basics: get you familiar with running Kotlin code, setting up, tools, and instructions that you can use to write basic programs. Next, we cover object oriented code: functions, lambdas, and properties — all while using Kotlin's new features. Then, we move on to null safety aspects and type parameterization. We show you how to destructure expressions and even write your own.

We also take you through i. Complete with a comprehensive introduction and projects covering the full set of Kotlin programming features, this book will take you through the fundamentals of Kotlin and get you up to speed in no time.

Learn Kotlin Programming covers the installation, tools, and how to write basic programs in Kotlin. You'll learn how to implement object-oriented programming in Kotlin and easily reuse your program or parts of it. The book explains DSL construction, serialization, null safety aspects, and type parameterization to help you build robust apps. 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.

If you want to really understand Kotlin, this is the book for you. 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. Put the words within or near the graphics they relate to, rather than on the bottom or on another page, and learners will be up to twice as likely to solve problems related to the content. Use a conversational and personalized style. Tell stories instead of lecturing. Use casual language. Which would you pay more attention to: a stimulating dinner-party companion, or a lecture?

Get the learner to think more deeply. In other words, unless you actively flex your neurons, nothing much happens in your head.

A reader has to be motivated, engaged, curious, and inspired to solve problems, draw conclusions, and generate new knowledge. And for that, you need challenges, exercises, and thought-provoking questions, and activities that involve both sides of the brain and multiple senses.

Your brain pays attention to things that are out of the ordinary, interesting, strange, eye-catching, unexpected. Touch their emotions. We now know that your ability to remember something is largely dependent on its emotional content. You remember what you care about. You remember when you feel something. Metacognition: thinking about thinking If you really want to learn, and you want to learn more quickly and more deeply, pay attention to how you pay attention.

Think about how you think. Learn how you learn. Most of us did not take courses on metacognition or learning theory when we were growing up. We were expected to learn, but rarely taught to learn. If you want to use what you read in this book, you need to remember what you read. To get the most from this book, or any book or learning experience, take responsibility for your brain. Your brain on this content. Crucial to your well-being. As important as a tiger. So just how DO you get your brain to treat Kotlin like it was a hungry tiger?

The slow way is about sheer repetition. You obviously know that you are able to learn and remember even the dullest of topics if you keep pounding the same thing into your brain. For example, studies show that putting words within the pictures they describe as opposed to somewhere else in the page, like a caption or in the body text causes your brain to try to makes sense of how the words and picture relate, and this causes more neurons to fire.

On the other hand, if the writing style is formal and dry, your brain perceives it the same way you experience being lectured to while sitting in a roomful of passive attendees.

No need to stay awake. And when text and pictures work together, we embedded the text in the pictures because your brain works more effectively when the text is within the thing it refers to, as opposed to in a caption or buried in the body text somewhere. We used redundancy, saying the same thing in different ways and with different media types, and multiple senses, to increase the chance that the content gets coded into more than one area of your brain.

We used concepts and pictures in unexpected ways because your brain is tuned for novelty, and we used pictures and ideas with at least some emotional content, because your brain is tuned to pay attention to the biochemistry of emotions. That which causes you to feel something is more likely to be remembered, even if that feeling is nothing more than a little humor, surprise, or interest.

We included activities, because your brain is tuned to learn and remember more when you do things than when you read about things.

We used multiple learning styles, because you might prefer step-by-step procedures, while someone else wants to understand the big picture first, and someone else just wants to see an example. But regardless of your own learning preference, everyone benefits from seeing the same content represented in multiple ways. We include content for both sides of your brain, because the more of your brain you engage, the more likely you are to learn and remember, and the longer you can stay focused.

Since working one side of the brain often means giving the other side a chance to rest, you can be more productive at learning for a longer period of time. We used people. In stories, examples, pictures, etc.

And your brain pays more attention to people than it does to things. The rest is up to you. Try new things. Note Cut this out and stick it on your refrigerator. Slow down. The more you understand, the less you have to memorize. Stop and think. Imagine that someone really is asking the question.

The more deeply you force your brain to think, the better chance you have of learning and remembering. Do the exercises. Write your own notes. We put them in, but if we did them for you, that would be like having someone else do your workouts for you. Use a pencil. Make this the last thing you read before bed. Or at least the last challenging thing.

Part of the learning especially the transfer to long-term memory happens after you put the book down. Your brain needs time on its own, to do more processing. If you put in something new during that processing time, some of what you just learned will be lost. Talk about it. Out loud. Speaking activates a different part of the brain. Better still, try to explain it out loud to someone else.

Drink water. Lots of it. Your brain works best in a nice bath of fluid. Dehydration which can happen before you ever feel thirsty decreases cognitive function. Listen to your brain. Pay attention to whether your brain is getting overloaded. Feel something. Your brain needs to know that this matters. Get involved with the stories. Make up your own captions for the photos.

Groaning over a bad joke is still better than feeling nothing at all. Write a lot of code! Coding is a skill, and the only way to get good at it is to practice. But try to solve the problem before you look at the solution. And definitely get it working before you move on to the next part of the book. Read me This is a learning experience, not a reference book. We begin by teaching some basic Kotlin concepts, and then we start putting Kotlin to work for you right away.

We cover the fundamentals of Kotlin code in Chapter 1. That way, by the time you make it all the way to Chapter 2, you are creating programs that actually do something. The rest of the book then builds on your Kotlin skills, turning you from Kotlin newbie to Kotlin ninja master in very little time. The redundancy is intentional and important.

One distinct difference in a Head First book is that we want you to really get it. The code examples are as lean as possible. We know how frustrating it is to wade through lines of code looking for the two lines you need to understand. The exercises and activities are NOT optional. Your brain will thank you for it. Not printed in the book, anyway. For some of them, there is no right answer, and for others, part of the learning experience is for you to decide if and when your answers are right.

In some of the Brain Power exercises, you will find hints to point you in the right direction. He is a regular speaker on the No Fluff, Just Stuff conference tour and a and JavaOne Rock Star, and has spoken at conferences all over the world.

Through his company, Kousen I. Acknowledgments Our editor: Heartfelt thanks to our awesome editor Jeff Bleiel for all his work and help. They made sure that what we covered was spot on, and kept us entertained along the way. We think the book is much better as a result of their feedback. Finally, our thanks to Kathy Sierra and Bert Bates for creating this extraordinary series of books, and for letting us into their brains. Our unique network of experts and innovators share their knowledge and expertise through books, articles, conferences, and our online learning platform.

Table of Contents the real thing how to use this book: Intro Your brain on Kotlin. From its first release, Kotlin has impressed programmers with its friendly syntax, conciseness, flexibility and power.

Your journey has just begun Classes are templates that allow you to create your own types of objects, and define their properties and functions. If you want to fully exploit polymorphism, you need to design using abstract classes and interfaces. Most applications include classes whose main purpose is to store data, so to make your coding life easier, the Kotlin developers came up with the concept of a data class.

And the great news is that Kotlin was designed with code-safety at its heart. Kotlin comes with a bunch of useful collections that give you more flexibility and greater control over how you store and manage groups of objects. Want to keep a resizeable list that you can keep adding to? Want to sort, shuffle or reverse its contents? Want to find something by name? Or do you want something that will automatically weed out duplicates without you lifting a finger?

If you want any of these things, or more, keep reading. If so, then you need lambdas. A lambda—or lambda expression—is a block of code that you can pass around just like an object. In situations such as these, coroutines are your new BFF. This means less time hanging around, a better user experience, and it can also make your application more scalable.

Appendix B Everybody knows that good code needs to work. But each code change that you make runs the risk of introducing fresh bugs that stop your code from working as it should. There are just a few more things we think you need to know. Before you put down the book, read through these tidbits. Welcome to Kotlinville Kotlin has been taking the programming world by storm. Despite being one of the youngest programming languages in town, many developers now view it as their language of choice.

So what makes Kotlin so special? Kotlin has many modern language features that make it attractive to developers. Well, why not do both? Kotlin lets you create object-oriented code that uses classes, inheritance and polymorphism, just as you can in Java. But it also supports functional programming, giving you the best of both worlds. Kotlin virtually eliminates the kinds of errors that regularly occur in other programming languages.

That means safer, more reliable code, and less time spent chasing bugs. So Kotlin is a modern, powerful and flexible programming language that offers many advantages. You can use Kotlin nearly everywhere Kotlin is so powerful and flexible that you can use it as a general-purpose language in many different contexts.

This is because you can choose which platform to compile your Kotlin code against. Android Alongside other languages such as Java, Kotlin has first-class support for Android. Client-side and server-side JavaScript You can also transpile—or translate and compile—Kotlin code into JavaScript, so that you can run it in a browser. You can use it to work with both client-side and server-side technology, such as WebGL or Node.

Native apps If you want to write code that will run quickly on less powerful devices, you can compile your Kotlin code directly to native machine code. This allows you to write code that will run, for example, on iOS or Linux. Kotlin includes basic language structures such as statements, loops and conditional branching.

Try out code in the Kotlin interactive shell. This is a free IDE from JetBrains, the people who invented Kotlin, and it comes with everything you need to develop Kotlin applications, including: Note There are many more features too, all there to make your coding life easier. Make sure you have the IDE open, and follow along with us. You also need to specify which platform you want your Kotlin project to target.

Then click on the Next button. Configure the project You now need to configure the project by saying what you want to call it, where you want to store the files, and what files should be used by the project.

This includes which version of Java should be used by the JVM, and the library for the Kotlin runtime. The folder structure is comprised of configuration files that are used by the IDE, and some external libraries that your application will use. It also includes a src folder, which is used to hold your source code.

Add a new Kotlin file to the project Before you can write any Kotlin code, you first need to create a Kotlin file to put it in. You will prompted for the name and type of Kotlin file you want to create. Whenever you write a Kotlin application, you must add a function to it called main, which starts your application. When you run your code, the JVM looks for this function, and executes it. You use the fun keyword for each new Kotlin function you create.

The fun keyword is followed by the name of the function, in this case main. Naming the function main means that it will be automatically executed when you run the application. The code in the braces after the function name tells the compiler what arguments if any the function takes. Add the main function to App. This opens the code editor, which you use to view and edit files: Then, update your version of App.

A: No. A Kotlin application might use dozens or even hundreds of files, but you may only have one with a main function—the one that starts the application running. When prompted, choose the AppKt option.

This builds the project, and runs the code. Assuming your code has no errors, compiling the code creates one or more class files that can run in a JVM. In our case, compiling App. Had we chosen to run it in another environment, the compiler would have compiled it into code for that environment instead. What can you say in the main function?

You can say all the normal things that you say in most programming languages to make your application do something. Use var for variables whose value you want to change, and val for ones whose value will stay the same.

Loop and loop and loop Kotlin has three standard looping constructs: while, do-while and for. The syntax for while loops is relatively simple. So long as some condition is true, you do everything inside the loop block. The loop block is bounded by a pair of curly braces, and whatever you need to repeat needs to be inside that block. Note If you just have one line of code in the loop block, you can omit the curly braces.

The key to a well-behaved while loop is its conditional test. A conditional test is an expression that results in a boolean value—something that is either true or false.

Simple boolean tests You can do a simple boolean test by checking the value of a variable using a comparison operator. These include: Notice the difference between the assignment operator a single equals sign and the equals operator two equals signs.

Update your version of App. The following text should appear in the output window at the bottom of the IDE: Before the loop. In the loop. After the loop. If you want each thing to print out on its own line, use println. If you want everything to stick together on the same line, use print. So depending on the values of x and y, either one statement or two will print out. Kotlin, however, takes things a step further.

Using if to return a value In Kotlin, you can use if as an expression, so that it returns a value. Previously, we used the following code to print a String: When you use if as an expression, you MUST include an else clause. Replace the code in your version of App. Unfortunately, a freak kitchen whirlwind has dislodged the magnets. Can you piece the code back together again? The REPL allows you to quickly try out snippets of code outside your main code.

As an example, try adding the following: println "I like turtles! BE the Compilera Each of the Kotlin files on this page represents a complete source file.

Mixed Messages A short Kotlin program is listed below. One block of the program is missing. Not all the lines of output will be used, and some lines of output may be used more than once. Draw lines connecting the candidate blocks of code with their matching output. Mixed Messages Solution A short Kotlin program is listed below. Bullet Points Use fun to define a function. Every application needs a function named main.

A String is a string of characters. You denote a String value by enclosing its characters in double quotes. Use var to define a variable whose value may change. Use val to define a value whose value will stay the same. A while loop runs everything within its block so long as the conditional test is true. Put a conditional test inside parentheses. Add conditional branches to your code using if and else. The else clause is optional. You can use if as an expression so that it returns a value.

In this case, the else clause is mandatory. Chapter 2. A variable is like a cup When you think of a variable in Kotlin, think of a cup. Cups come in many different shapes and sizes—big cups, small cups, the giant disposable cups that popcorn comes in at the movies—but they all have one thing in common: a cup holds something. Declaring a variable is like ordering a drink from Starbucks. This is so we can use that name in our code. If we initially set your variable to 2, for example, can we later set it to 3?

Or should it remain 2 forever? Is it an integer? A String? Or something more complex? For this type-safety to work, the compiler needs to know the type of the variable. To create a variable, the compiler needs to know its name, type and whether it can be reused. The value is transformed into an object The variable stays this type forever. Next, the object is assigned to the variable. How does this happen? A reference to the object goes into the variable instead: As the variable holds a reference to the object, this gives it access to the object.

But if you use the var keyword instead, you can assign another value to the variable. Each type can hold a fixed number of bits. Bytes can hold 8 bits, for example, so a Byte can hold integer values from to Ints, on the other hand, can hold 32 bits, so an Int can hold integer values from -2,,, to 2,,, If the integer you assign is too large to fit into an Int, it will use a Long instead.

Floating points There are two basic floating-point types: Float and Double. Floats can hold 32 bits, whereas Doubles can hold 64 bits. Char variables are used for single characters. String variables are used for multiple characters strung together.

But there are times when you need to explicitly tell the compiler what type of variable you want to create. You may want to use Bytes or Shorts instead of Ints, for example, because they are more efficient. Or you may want to declare a variable at the start of your code, and assign a value to it later on. Similarly, if you want to declare a Byte variable, you use code like this: var tinyNum: Byte Declaring the type AND assigning a value The above examples create variables without assigning values to them.

A reference to the Short object is then put into the variable. When you assign a value to a variable, you need to make sure that the value is compatible with the variable. Assigning an initial value to a variable is called initialization. As an example, if you try to assign a floating-point number such as 3.

This is particularly important when you want to assign the value of one variable to another. The Kotlin compiler will only let you assign a value to a variable if the value and variable are compatible. Is that not the case with Kotlin? In Kotlin, numbers are objects, and the variable holds a reference to the object, not the object itself.

A: Because it makes your code safer, and less prone to bugs. Q: In Java, you can treat char primitives as numbers. Can you do the same for Chars in Kotlin? A: No, Chars in Kotlin are characters, not numbers. Q: Can I name my variables anything I want? Naming your variable while, for example, is just asking for trouble. Assigning a value to another variable When you assign the value of one variable to another, you need to make sure that their types are compatible.

Rather than create a second Int object, the value of variable x is assigned to variable y. But what does this mean? The x variable contains a reference to an Int object with a value of 5, not a Long object. We know that the object has a value of 5, and we know that 5 fits into a Long object.

But because the z variable is a different type to the Int object, the compiler gets upset and refuses to compile the code. So how do you assign the value of one variable to another if the variables are of different types? We need to convert the value Suppose you want to assign the value of an Int variable to a Long. In order for the code to compile, you first have to convert the value to the right type. So if you want to assign the value of an Int variable to a Long, you first have to convert its value to a Long.

An object has state and behavior Being an object means that it has two things: state and behavior. A numeric object, for example, has a numeric value, such as 5, 42 or 3. A Boolean is either true or false. A String can be capitalized, for example. Numeric objects know how to perform basic math, and convert their value into an object of a different numeric type.

How to convert a numeric value to another type In our example, we want to assign the value of an Int variable to a Long. So if you want to assign the value of an Int variable to a Long, you use code like this: The dot operator. A reference to the Long object gets put into the z variable.

But what if the new object is too small to contain the value? Watch out for overspill Trying to put a large value into a small variable is like trying to pour a bucket-load of coffee into a tiny teacup. Some of the coffee will fit into the cup, but some will spill out. Suppose you want to put the value of a Long into an Int. As you saw earlier in the chapter, a Long can hold larger numbers than an Int. The compiler assumes this is deliberate, so the code compiles. Circle the lines that are invalid, and say why they stop the code from being compiled.

Suppose you wanted to store the names of fifty ice cream flavors, or the bar codes of all the books in a library. To do that with variables would quickly get awkward. Instead, you can use an array. Arrays are great if you want a quick and dirty group of things.

You can think of an array as being like a tray of cups, where each item in the array is a variable: How to create an array You create an array using the arrayOf function. This starts the wizard you saw in Chapter 1. When prompted, choose the options to create a Kotlin project that targets the JVM. Add the code to PhraseOMatic. Add the code below to PhraseOMatic. We then use toInt to force the result to be an integer. String Templates Up Close String templates provide a quick and easy way of referring to a variable from inside a String.

In this case, you enclose the expression in curly braces. So String templates allow you to construct complex Strings with very little code. Before version 1. For applications running on a JVM, however, you could use the random method from the Java Math library, as we have. The compiler looks at the type of each item in the array, and infers what type of items the array should contain forever. As an example, suppose you wanted to declare an array that holds Byte values. As you already know, a variable holds a reference to an object.

When you declare a variable using var, you can update the variable so that it holds a reference to a different object instead. If the variable holds a reference to an array, this means that you can update the variable so that it refers to a different array of the same type. A reference to the new array gets put into the myArray variable, replacing the previous reference. So what happens if we use the variable using val instead? When you declare an array using val, you can no longer update the variable so that it holds a reference to a different array.

But even though the variable maintains a reference to the same array, the array itself can still be updated. You can, however, still update the object itself.

But this instruction only applies to the variable itself. If the variable holds a reference to an array, the items in the array can still be updated. As an example, suppose you have the following code: This creates a variable named myArray that holds a reference to an array of Ints.

The third item in the array is then successfully updated to 6, as the array itself can be updated: Now that you know how arrays work in Kotlinville, have a go at the following exercises. BE the Compiler Each of the Kotlin files on this page represents a complete source file. Code Magnets A working Kotlin program is all scrambled up on the fridge.

Some objects may be referred to more than once. Draw lines connecting the variables to their objects. Code Magnets Solution A working Kotlin program is all scrambled up on the fridge. Bullet Points In order to create a variable, the compiler needs to know its name, its type, and whether it can be reused. A variable holds a reference to an object. An object has state and behavior. Its behavior is exposed through its functions.

Defining the variable with val means the variable holds a reference to the same object forever. You can convert one numeric type to another. The first item in an array has an index of 0. String templates provide a quick and easy way of referring to a variable or evaluating an expression from inside a String. Chapter 3. This is because: Each function is a named section of code that performs a specific task.

As an example, you could write a function named max that determines the highest value out of two values, and then call this function at various stages in your application. Setup: When the application is launched, the game chooses Rock, Paper or Scissors at random. It then asks you to choose one of these options. The rules: The game compares the two choices. If they are the same, the result is a draw. A high-level design of the game Before we start writing the code for the game, we need to draw up a plan of how it will work.

First, we need to figure out the general flow of the game. Ask the user for their choice. Please enter one of the following: Rock Paper Scissors. Paper Print the result.



0コメント

  • 1000 / 1000