Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing
By Tim Lavers
()
About this ebook
Teach yourself programming starting with the basics and progressing to a series of exciting projects using Kotlin, one of today's hottest programming languages. This book starts with the absolute basics and then introduces just enough syntax to get into some fascinating projects. These include text processing: a statistical analysis of Jane Austen's novels, solving anagrams, and working with palindromes; image processing: cropping and resizing images, and pixel transformation; and computer vision: finding digits, parsing images, and reading speed signs.
The projects are developed in tiny steps and complete solutions are provided. Some of these projects include core data science concepts, giving you skills in one of the most important areas of modern programming. Along the way you’ll cover functional programming, object-oriented programming (OOP), refactoring, and writing unit tests.After reading Learn to Program with Kotlin, you'll come away with practical insights and code to get you started right away with programming using Kotlin for your own projects.
What You Will Learn
- Gain the basics of Kotlin using the IntelliJ Java IDE
- Implement OOP with Kotlin along with unit testing and code refactoring using a series of text-related projects
- Harness functional programming with Kotlin by building an image-processing library
- Write software to locate and read speed signs in photos
Who Is This Book For
Anyone who wants to learn how to program or code from scratch. Also great for experienced programmers who want to know more about Kotlin.Related to Learn to Program with Kotlin
Related ebooks
Learn To Code Rating: 0 out of 5 stars0 ratingsDeep Learning with Swift for TensorFlow: Differentiable Programming with Swift Rating: 0 out of 5 stars0 ratingsLearn Python Programming the Easy and Fun Way Rating: 0 out of 5 stars0 ratingsPractical Scientific Computing Rating: 0 out of 5 stars0 ratingsPYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Go Programming Cookbook Rating: 0 out of 5 stars0 ratingsGo Programming Cookbook: Over 75+ recipes to program microservices, networking, database and APIs using Golang Rating: 0 out of 5 stars0 ratingsLearn Android Studio 4: Efficient Java-Based Android Apps Development Rating: 0 out of 5 stars0 ratingsPractical Machine Learning in JavaScript: TensorFlow.js for Web Developers Rating: 0 out of 5 stars0 ratingsBasic Guide to Programming Languages Python, JavaScript, and Ruby Rating: 0 out of 5 stars0 ratingsSoftware Engineering for Absolute Beginners: Your Guide to Creating Software Products Rating: 0 out of 5 stars0 ratingsThe Struts Framework: Practical Guide for Java Programmers Rating: 0 out of 5 stars0 ratingsBasic Python for Data Management, Finance, and Marketing: Advance Your Career by Learning the Most Powerful Analytical Tool Rating: 0 out of 5 stars0 ratingsInstant Play Framework Starter Rating: 0 out of 5 stars0 ratingsGroovy for Domain-specific Languages - Second Edition Rating: 0 out of 5 stars0 ratingsLearn R By Coding Rating: 0 out of 5 stars0 ratingsTest-Driven iOS Development with Swift Rating: 5 out of 5 stars5/5Mastering Sublime Text Rating: 0 out of 5 stars0 ratingsReinforcement Learning Algorithms with Python: Learn, understand, and develop smart algorithms for addressing AI challenges Rating: 0 out of 5 stars0 ratingsDart Essentials Rating: 0 out of 5 stars0 ratingsLearn Kotlin for Android Development: The Next Generation Language for Modern Android Apps Programming Rating: 0 out of 5 stars0 ratingsARM® Cortex® M4 Cookbook Rating: 4 out of 5 stars4/5Learn AI-assisted Python Programming: With GitHub Copilot and ChatGPT Rating: 0 out of 5 stars0 ratingsDeveloping Web Components with TypeScript: Native Web Development Using Thin Libraries Rating: 0 out of 5 stars0 ratingsGetting to Know Vue.js: Learn to Build Single Page Applications in Vue from Scratch Rating: 0 out of 5 stars0 ratingsModern C Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library Rating: 0 out of 5 stars0 ratingsIntroduction to Python 2018 Edition Rating: 4 out of 5 stars4/5
Computers For You
Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 5 out of 5 stars5/5How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5Network+ Study Guide & Practice Exams Rating: 4 out of 5 stars4/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 0 out of 5 stars0 ratingsThe ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 0 out of 5 stars0 ratings101 Awesome Builds: Minecraft® Secrets from the World's Greatest Crafters Rating: 4 out of 5 stars4/5Creating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Ultimate Guide to Mastering Command Blocks!: Minecraft Keys to Unlocking Secret Commands Rating: 5 out of 5 stars5/5AP Computer Science Principles Premium, 2024: 6 Practice Tests + Comprehensive Review + Online Practice Rating: 0 out of 5 stars0 ratingsCompTIA Security+ Practice Questions Rating: 2 out of 5 stars2/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5CompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratingsChildhood Unplugged: Practical Advice to Get Kids Off Screens and Find Balance Rating: 0 out of 5 stars0 ratingsChatGPT Ultimate User Guide - How to Make Money Online Faster and More Precise Using AI Technology Rating: 0 out of 5 stars0 ratingsPractical Lock Picking: A Physical Penetration Tester's Training Guide Rating: 5 out of 5 stars5/5Elon Musk Rating: 4 out of 5 stars4/5Dark Aeon: Transhumanism and the War Against Humanity Rating: 5 out of 5 stars5/5The Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5Master Builder Roblox: The Essential Guide Rating: 4 out of 5 stars4/5Hacking: Ultimate Beginner's Guide for Computer Hacking in 2018 and Beyond: Hacking in 2018, #1 Rating: 4 out of 5 stars4/5
Reviews for Learn to Program with Kotlin
0 ratings0 reviews
Book preview
Learn to Program with Kotlin - Tim Lavers
Part IBasics
Basics
In Part I, we set up Kotlin and learn the most important features of the language.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
T. LaversLearn to Program with Kotlinhttps://doi.org/10.1007/978-1-4842-6815-5_1
1. Getting Started
Tim Lavers¹
(1)
Woonona, NSW, Australia
In this chapter, we set up our programming environment and get our first program running.
1.1 What Is Programming?
A computer program is a set of instructions that tell a computer to perform an action such as showing an image or printing out some text.
These instructions are written using special sets of words and symbols, called programming languages. In this book, we are going to use a language called Kotlin. Kotlin is quite new and is closely related to another language, called Java, which is extremely popular in industry and in universities around the world. While Java is an excellent language, it is over 20 years old, which is ancient in computing terms. Additionally, since Java was first developed, there have been many improvements in programming that Kotlin takes advantage of. These improvements mean that Kotlin programs tend to be simpler than their Java equivalents, and many sources of mistakes are avoided outright.
Unlike human beings, computers do not understand vague instructions and are not able to move beyond the simple typographical errors that we easily make. This can make programming a very frustrating task, as even tiny mistakes, such as a missing comma, can stop an otherwise perfect program from working. To avoid these problems, some introductory programming books use very simple languages or even Lego-style visual programming tools in which syntax errors are not possible.
We’ve decided to stick with Kotlin in this book because by learning it you will be gaining skills in a language that is the first choice for thousands of other programmers and can be used to program lots of different kinds of devices, such as personal computers (obviously), Android devices, microcomputers, and so on. Also, there are lots of code samples that can be found for solving particular problems.
To handle the problems brought about by the complexity of a full-powered language, we will work by modifying existing programs using a code editor that highlights errors and offers sensible corrections.
1.2 Installing Java
As mentioned before, Kotlin is related to an older language called Java. In fact, in order to write and run Kotlin programs, we will need to install the programming tools for Java. These are bundled as what is called the Java Development Kit or Java Platform, or JDK, which is a free download from Oracle at the site www.oracle.com/java/technologies/javase-downloads.html.On this page, shown in Figure 1-1, click the JDK Download
link. This will take you to a page that provides download links for a variety of operating systems. Choose the one that suits your system and download and install the software.
Figure 1-1
The Java download site. Click the JDK Download
link
1.3 Installing Git
Git is a program that is used to share source code between programmers. All of the code in this book can be obtained using Git. This is extremely convenient, but the downside is that we need to install another piece of software. To begin, visit https://git-scm.com/. From this site, download the version for your operating system. Running the installer is a pretty lengthy process, as there are lots of screens that present different setup options. Just accept the default options at each screen.
1.4 Installing IntelliJ
A good code editor is extremely helpful in avoiding and correcting errors in programs. IntelliJ is the best code editor for Kotlin and is very popular with professional programmers. We will be using the Community Edition
of the tool, which is free for noncommercial use. IntelliJ can be downloaded from the JetBrains website, www.jetbrains.com/idea/, and the installation process is simple and well documented.
1.5 Our First Program
Our first program is available from a Git repository that can be opened with IntelliJ. The IntelliJ tool for opening a Git repository is available from the Welcome to IntelliJ IDEA
screen shown in Figure 1-2.
Figure 1-2
The IntelliJ welcome screen
To get the first program:
1.
Click the Get from VCS button.
2.
Wait for the Get from Version Control
dialog, shown in Figure 1-3, to show.
3.
Copy this address: https://github.com/Apress/learn-to-program-w-kotlin-basics.git into the URL field.
4.
Create a new directory, also known as a folder
in Windows, and copy the location into the Directory field.
5.
Press the Clone button.
../images/508289_1_En_1_Chapter/508289_1_En_1_Fig3_HTML.jpgFigure 1-3
The IntelliJ dialog for getting a Git repository
After some time, which depends on your Internet connection and computer speed, IntelliJ will present the downloaded project, as in Figure 1-4. In the bottom right-hand corner, there might be a pop-up (not shown here) asking about adding files to Git. Just click the Don’t ask again option.
../images/508289_1_En_1_Chapter/508289_1_En_1_Fig4_HTML.jpgFigure 1-4
The project in IntelliJ. This part of the IntelliJ user interface is called the project tree. It contains the source files for our programs
The upper left-hand side of this screen has what is called the project tree. We will use this later to locate our first program and run it. The project tree can be shown or hidden by pressing the Alt and 1 keys at the same time. If, for whatever reason, the project tree is not showing, use this key combination to reveal it. If that does not work, use the menu Windows ➤ Restore Default Layout to put things right.
1.6 Changing the Appearance of IntelliJ
As with many programs, the appearance of IntelliJ is configurable. This is done by selecting a visual theme.
The default theme uses the dark colors that can be seen in the preceding screenshots—in fact, the theme is called Darcula.
To change the theme, use the menu File ➤ Settings to display the Settings dialog. Then select Appearance in the tree on the left of the settings screen. The Theme drop-down has a number of built-in themes from which you can select one you like, as shown in Figure 1-5. In the interests of producing clearer screenshots, I will be using the IntelliJ Light
theme from now on, as shown.
Figure 1-5
Setting the visual theme
1.7 Troubleshooting
If IntelliJ was installed before Git, you may get an error message about the path to the Git executable not being found. This can generally be fixed by setting the path within IntelliJ. To do this, choose File ➤ Settings and then select Git under the Version Control heading, as in Figure 1-6. The Test button in the top right-hand corner can be used to check that IntelliJ knows where Git is installed. If this test fails, you may need to adjust the setup in IntelliJ by changing the Path to Git executable value.
../images/508289_1_En_1_Chapter/508289_1_En_1_Fig6_HTML.jpgFigure 1-6
Configuring Git in IntelliJ
../images/508289_1_En_1_Chapter/508289_1_En_1_Fig7_HTML.jpgFigure 1-7
The program is run by clicking the green triangle
1.8 Running Our First Program
By clicking the folder icons (they look like > signs) in the project tree, you should be able to navigate to the file FirstProgram.kt. Double-click this to open it in the main editor pane. To run the program, click the little green triangle at line 7 of the program text. A pop-up will show, with the option Run ‘FirstProgramKt’. Select this option.
After a half-minute or so of background activity, you should see an application frame with a pattern of black and white squares. Congratulations! You’ve got the first program running! If you click the small cross at the upper right-hand corner, the display will close and the program will terminate.
../images/508289_1_En_1_Chapter/508289_1_En_1_Fig8_HTML.jpgFigure 1-8
Our first program shows a simple pattern of black and white tiles
1.9 Source Code for Our Program
As a wrap-up for this chapter, let’s have a quick look at the code for our program, just to get a bit more familiar with what Kotlin code looks like. The aim here is just to understand a little of the broad outline of a program. The details will come later.
1 package lpk.basics
2
3 import javax.swing.ImageIcon
4 import javax.swing.JFrame
5 import javax.swing.SwingUtilities
6
7 fun main() {
8 SwingUtilities.invokeLater { FirstProgram().doLaunch() }
9 }
10 class FirstProgram {
11
12 fun tileColors() : Array
13 return arrayOf(
14 arrayOf(0, 255),
15 arrayOf(255, 0)
16 )
17 }
18
19 fun doLaunch() {
20 val frame = JFrame(Basics
)
21 frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
22 frame.iconImage = ImageIcon(./src/lpk/basics/icon.png
).image
23 frame.add(TilePanel(tileColors()))
24 frame.pack()
25 frame.isVisible = true
26 }
27 }
Note that some of the import statements (lines 3 to 5) might not be showing. Instead, they might appear as a collapsed code block that can be expanded by clicking the + sign.
../images/508289_1_En_1_Chapter/508289_1_En_1_Fig9_HTML.jpgFigure 1-9
The import statements might be hidden as a collapsed code block
Even this short program contains a lot of detail that will be totally incomprehensible to a first-time programmer. Don’t worry! You don’t need to understand everything at once. The main parts of the program can be understood in the following terms:
1.
The first line tells the system what package our program belongs in. The complete name of a program includes its package, just as the combination of street name plus other details makes a postal address unique.
2.
The import statements let the system know what other programs are needed in our code. All software that does anything remotely complex, such as showing a user interface, makes use of prebuilt components. The import statements are used to make them available to our code.
3.
The block containing tileColors() sets up a grid of color values. We’ll look at this in detail in the next few chapters.
4.
Lines 19 to 26 tell the system how to turn the block of colors into a user interface element that can be drawn on the screen.
5.
The function called main on line 7 is the starting point for the system to launch the program.
In the next chapter, we will begin modifying this code to produce new patterns.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
T. LaversLearn to Program with Kotlinhttps://doi.org/10.1007/978-1-4842-6815-5_2
2. Simple Patterns
Tim Lavers¹
(1)
Woonona, NSW, Australia
In this chapter, we will see how black, white, and other shades of gray can be represented in Kotlin. This will allow us to modify our program from the previous chapter to show different tile patterns. In making these changes, we will be getting familiar with basic Kotlin syntax and with the programming environment.
2.1 Shades of Gray
Software engineering is about modeling aspects of the real world, such as colors, shapes, sounds, and so on, using simple mathematical constructs such as numbers. For now, we are working with shades of gray, and there are many ways that these can be represented in a computer program, for example:
1.
Giving specific shades names such as black, white, light gray, dark gray, and so on
2.
Representing black by 0, white by 1, and intermediate shades by numbers between these values
3.
Representing black as 0 and white as 255, with each intermediate shade given by a whole number between these values
The first method is fine if there are just a few shades used in a program. In fact, a similar approach is used in writing web pages. The second method is used in a lot of applications but can be confusing as there are infinitely many numbers between 0 and 1, but only a finite set of shades can be displayed on computer screens, so different decimals might end up producing the same shade. The third approach allows for 256 different shades of gray, which is probably as many as can be discerned by most people, with each number representing a different shade, and a fairly simple way of estimating the shade for a value. This is the model that we have used in our program.
The part of our program that sets up the colors of the squares that are to be displayed is
1 fun tileColors() : Array
2 return arrayOf(
3 arrayOf(0, 255),
4 arrayOf(255, 0)
5 )
6 }
This code is an example of what is called a function , which is a block of code that does one job, and is called from one or more places in a program. Let’s look at this function in detail.
1.
The keyword fun identifies this as a function.
2.
tileColors is the name of the function. When we want to use it, we call it by this name.
3.
The empty brackets () signal the end of the function name and mean that the function has no inputs. Inputs to functions are usually called parameters (when talking of a function definition) or arguments (when talking of an actual call to a function).
4.
The complicated bit Array
5.
The left brace, {, is the start of the function body, which is the set of instructions in which the logic of the function is implemented.
6.
The word return defines what the output, or result, of the function will be.
7.
The word arrayOf on line 2 is a call to another function, called arrayOf, which produces an array from whatever is passed into it.
8.
The left bracket ( at the end of line 2 is the start of the list of arguments that we are passing into the arrayOf function. This left bracket is matched by the right bracket on line 5.
9.
On lines 3 and 4, we are setting up the arguments to the arrayOf function call made on line 2. We are passing in two arguments, one from line 3 and one from line 4. The comma at the end of line 3 separates these.
10.
Line 3 creates an Array of two Ints. This is done with a call to the arrayOf function. The arguments in this call are 0 and 255.
11.
Line 4 creates an array that has 255 in the first position and 0 in the second.
12.
The closing right brace on line 6 completes the function.
There are lots of details here. Don’t let them overwhelm you! By writing code (and making mistakes), you will become familiar with this syntax. Let’s make some changes to this program now.
2.2 Changing the Pattern
Now it’s your turn for some coding! By modifying the numbers on lines 3 and 4 of the preceding code block, you can change the program from Chapter 1 to produce different tile patterns.
If you make an error, you can just use the menu sequence Edit ➤ Undo Typing to get back to a version of the program that worked. You can also undo changes using the key combination Ctrl + z.
Tip
The solutions to these challenges are at the end of this chapter.
PROGRAMMING CHALLENGE 2.1
Change the program so that it produces this pattern:
../images/508289_1_En_2_Chapter/508289_1_En_2_Figa_HTML.jpgPROGRAMMING CHALLENGE 2.2
Change the program to give
../images/508289_1_En_2_Chapter/508289_1_En_2_Figb_HTML.jpgPROGRAMMING CHALLENGE 2.3
Change the program so that it produces this 3-by-3 pattern:
../images/508289_1_En_2_Chapter/508289_1_En_2_Figc_HTML.jpgPROGRAMMING CHALLENGE 2.4
If we change the getTileColors function to
fun tileColors() : Array
return arrayOf(
arrayOf(0, 64),
arrayOf(128, 192)
)
}
we get this pattern:
../images/508289_1_En_2_Chapter/508289_1_En_2_Figd_HTML.jpgModify the code again to give
../images/508289_1_En_2_Chapter/508289_1_En_2_Fige_HTML.jpg2.3 Solutions to Challenges
For each challenge, we need only change the implementation of the getTileColors function. The changes are as follows.
SOLUTION 2.1
The top-left and bottom-right tiles need to have shade 255, whereas the other tiles are black and so have value 0:
fun tileColors() : Array
return arrayOf(
arrayOf(255, 0),
arrayOf(0, 255)
)
}
SOLUTION 2.2
In this pattern, the only white tile is in the bottom-right corner. This corresponds to the second item in the second array:
fun tileColors() : Array
return arrayOf(
arrayOf(0, 0),
arrayOf(0, 255)
)
}
SOLUTION 2.3
This pattern has three rows and columns, so we need three arrays of three elements each:
fun tileColors() : Array
return arrayOf(
arrayOf(0, 255, 0),
arrayOf(255, 0, 255),
arrayOf(0, 255, 0)
)
}
SOLUTION 2.4
In the following code, we’ve used 192 for the brightest tile and then 128 and 64 for the dark gray tiles. Slightly different values will give similar patterns to that shown.
fun tileColors() : Array
return arrayOf(
arrayOf(0, 64),
arrayOf(128, 192)
)
}
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
T. LaversLearn to Program with Kotlinhttps://doi.org/10.1007/978-1-4842-6815-5_3
3. Arrays and Loops
Tim Lavers¹
(1)
Woonona, NSW, Australia
In the previous chapter, we worked on a program that built patterns of black and white tiles that corresponded to the elements of a square array. In this chapter, we will introduce a powerful syntax that allows us to build larger patterns from shorter programs.
3.1 Array Indexes
Recall from Chapter 2 that an array is a list of values. An array of arrays is effectively a grid, and our programs so far have used these to represent rectangular patterns of black and white tiles. In these programs, we have used the library function arrayOf to create arrays. However, we can also create arrays from scratch, for example:
1 fun tileColors(): Array
2 val shades = Array(2) {
3 Array(2) { 0 }
4 }
5 shades[0][0] = 192
6 shades[0][1] = 128
7 shades[1][0] = 64
8 shades[1][1] = 0
9 return shades
10 }
This