Tran D. Principles, Policies, and Applications of Kotlin Programming 2023
Tran D. Principles, Policies, and Applications of Kotlin Programming 2023
Applications of Kotlin
Programming
Jun-Ho Huh
Korea Maritime and Ocean University, South Korea
Names: Tran, Duy Thanh, 1984- author. | Huh, Jun-Ho, 1984- author.
Title: Principles, policies, and applications of Kotlin programming / by
Duy Thanh Tran and Jun-Ho Huh.
Description: Hershey, PA : Engineering Science Reference, an imprint of IGI
Global, [2023] | Includes bibliographical references and index. |
Summary: “This book is a guide to learning and understanding the Kotlin
programming language”-- Provided by publisher.
Identifiers: LCCN 2022023479 (print) | LCCN 2022023480 (ebook) | ISBN
9781668466872 (h/c) | ISBN 9781668466889 (s/c) | ISBN 9781668466896
(ebook)
Subjects: LCSH: Kotlin (Computer program language) | Android (Electronic
resource) | Smartphones--Programming.
Classification: LCC QA76.73.K68 T73 2023 (print) | LCC QA76.73.K68
(ebook) | DDC 005.13/3--dc23/eng/20220804
LC record available at https://lccn.loc.gov/2022023479
LC ebook record available at https://lccn.loc.gov/2022023480
This book is published in the IGI Global book series Advances in Systems Analysis, Software
Engineering, and High Performance Computing (ASASEHPC) (ISSN: 2327-3453; eISSN: 2327-
3461)
The theory and practice of computing applications and distributed systems has
emerged as one of the key areas of research driving innovations in business,
engineering, and science. The fields of software engineering, systems analysis,
and high performance computing offer a wide range of applications and
solutions in solving computational problems for any modern organization.
The Advances in Systems Analysis, Software Engineering, and High
Performance Computing (ASASEHPC) Book Series brings together
research in the areas of distributed computing, systems and software
engineering, high performance computing, and service science. This collection
of publications is useful for academics, researchers, and practitioners seeking
the latest practices and knowledge in this field.
Coverage
• Performance Modelling
IGI Global is currently accepting
• Human-Computer Interaction
manuscripts for publication within this
• Enterprise Information Systems
series. To submit a proposal for a volume in
• Computer System Analysis
this series, please contact our Acquisition
• Metadata and Semantic Web
Editors at [email protected] or
• Virtual Data Systems
visit: http://www.igi-global.com/publish/.
• Network Management
• Distributed Cloud Computing
• Software Engineering
• Parallel Architectures
The Advances in Systems Analysis, Software Engineering, and High Performance Computing (ASASEHPC) Book
Series (ISSN 2327-3453) is published by IGI Global, 701 E. Chocolate Avenue, Hershey, PA 17033-1240, USA, www.
igi-global.com. This series is composed of titles available for purchase individually; each title is edited to be contextually
exclusive from any other title within the series. For pricing and ordering information please visit http://www.igi-global.
com/book-series/advances-systems-analysis-software-engineering/73689. Postmaster: Send all address changes to above
address. Copyright © 2023 IGI Global. All rights, including translation in other languages reserved by the publisher. No
part of this series may be reproduced or used in any form or by any means – graphics, electronic, or mechanical, including
photocopying, recording, taping, or information and retrieval systems – without written permission from the publisher,
except for non commercial, educational use, including classroom teaching purposes. The views expressed in this series
are those of the authors, but not necessarily of IGI Global.
Titles in this Series
For a list of additional titles in this series, please visit:
http://www.igi-global.com/book-series/advances-systems-analysis-software-engineering/73689
Preface.................................................................................................................xiii
Acknowledgment................................................................................................ xix
Chapter 1
Introducing Kotlin Programming Language...........................................................1
Chapter 2
Data Types and Variables.....................................................................................31
Chapter 3
Conditional Execution..........................................................................................53
Chapter 4
Loop Executions...................................................................................................75
Chapter 5
Exception Handling............................................................................................100
Chapter 6
Commonly Important Libraries..........................................................................116
Chapter 7
String Processing................................................................................................131
Chapter 8
Array Processing.................................................................................................147
Chapter 9
Collections..........................................................................................................159
Chapter 10
Object-Oriented Programming in Kotlin............................................................169
Chapter 11
File Processing....................................................................................................241
Chapter 12
Graphic User Interface........................................................................................305
Chapter 13
Vert.X for Kotlin Restful API.............................................................................394
Index................................................................................................................... 455
Detailed Table of Contents
Preface.................................................................................................................xiii
Acknowledgment................................................................................................ xix
Chapter 1
Introducing Kotlin Programming Language...........................................................1
This chapter introduces Kotlin programming language and its strengths, such as
brevity, saftey, versatility, and interoperability features. Readers will discover how
to install Kotlin programming tools, how to create projects, program sample projects
and check the output results. At the same time, this chapter also presents the types
of notes when programming such as single-line comment, multi-line comments, and
KDoc comments; comments are one of the important requirements of the software
industry. Readers will be familiar with simple and easy-to-understand examples so
that readers can practice after reading and using the functions in the IntelliJ IDEA
programming tool. Finally, there are exercises listed at the end of the chapter to help
readers practice more programming skills with Kotlin.
Chapter 2
Data Types and Variables.....................................................................................31
and easy-to-understand sample code for easy access, and at the end of the chapter
there are practice exercises to improve programming skills.
Chapter 3
Conditional Execution..........................................................................................53
Almost every programming language has to use conditional constructs to handle the
business of the software. Basically, the operating mechanism of these conditional
structures is the same, but with the Kotlin programming language, it has added a
lot of extended and very convenient features, it helps programmers more optimal
options in the process of processing business. This chapter will present conditional
constructs about simple if statement, if/else statement, nested conditionals, expression
and block form {}, and when structure. The when structure has been greatly improved
in Kotlin, it provides a lot of use cases so that programmers can easily handle
business tasks more optimally, such as when with if/else statement, group multiple
conditions. For each conditional structure, this chapter provides simple examples
and detailed explanations to help readers understand the working mechanism of the
conditional structure and apply them to specific business handling. At the end of
the chapter, there is a list of exercises to help readers improve programming skills
on conditional structures.
Chapter 4
Loop Executions...................................................................................................75
Similar to the conditional structure, in all software, programmers have to use loop
structures to handle repetitive tasks according to certain rules. When dealing with
list data such as character strings, numeric arrays, list of objects, etc. then loops will
be used. Kotlin provides loop controls such as for, while, do while and abnormal
loop termination. The loop executions are greatly improved, such as for loops that
are divided many types such as closed range, half-open range, step and downTo
navigation. And these kinds cover most of the loop handling cases, making it easy for
programmers to use them optimally. This chapter also demonstrates how to handle
break statement and continue statement in abnormal loop termination, these are very
important statements in loop handling. This chapter also provides complete code and
detailed explanations for each loop, making it easy for learners to understand and
practice loops. At the end of the chapter, there are exercises to help readers practice
programming skills for loops and consolidate the knowledge in previous chapters.
Chapter 5
Exception Handling............................................................................................100
In the process of programming, most of mistakes can be raised. And making errors
while programming is inevitable. Therefore, programmers need to have ways to
distinguish the types of errors and how to handle errors. This chapter will present
error levels such as compiler error, runtime exception error, and exception logic error.
This chapter also provides techniques for catching errors such as try catch structure
and throw exception technique. Illustrative codes are presented for how to handle
this error for readers to easily grasp. However, most programming tools support
debugging functions, and this tool makes it easy for programmers to find errors and
from there it helps programmers easily find the solutions to fix errors quickly and
accurately, so this chapter presents IntelliJ IDEA’s debugging tool. At the end of the
chapter there are exercises to help readers improve the skills in exception handling.
Chapter 6
Commonly Important Libraries..........................................................................116
Every programming language has a set of libraries that will help programmers quickly
solve certain tasks, and programmers must certainly use it because programmers
either cannot write some libraries or it takes a long time; so programmers must
know how to use them. These libraries may be in the JVM or KotlinJavaRuntime or
in any other external library. In this chapter, the book will present some commonly
used libraries, such as numeric data processing library, date processing library, math
processing library, random number processing library, and string processing library.
And there are many other processing libraries—readers can do more research about
those libraries. At the end of the chapter there are exercises to help readers improve
the skills in important libraries commonly.
Chapter 7
String Processing................................................................................................131
Chapter 8
Array Processing.................................................................................................147
Array is one of the very important data in software processing, it will be used to store
data in the form of a list. Almost all programming languages support array processing,
and so does the Kotlin language. However, with Kotlin, arrays are a very powerful
data type, which overcome many disadvantages compared to other programming
languages such as C++, C#, Java, etc. The book has briefly mentioned some of the
array types that are built-in in Kotlin, such as: CharArray, BooleanArray, ByteArray,
ShortArray, IntArray, LongArray, FloatArray, and DoubleArray. Depending on the
purpose of use, programmers can choose different types of arrays; to help readers
easily understand how to declare and use one-dimensional arrays in Kotlin, the book
will use IntArray to illustrate in the examples below. Other types of arrays Readers
can infer. At the end of the chapter, there are exercises to help readers improve
programming skills to handle arrays.
Chapter 9
Collections..........................................................................................................159
Chapter 10
Object-Oriented Programming in Kotlin............................................................169
acts as a unit of combined methods and properties. Kotlin is like other programming
languages that support object-oriented programming. OOP is a general concept;
programming language is just one of the tools to implement that concept. This
means that if readers already understand OOP, then C #, Java, Kotlin, etc. will
share this concept for implementation. The chapter provides illustrative and detailed
explanations to help readers easily understand OOP. And at the end of the chapter,
there are exercises to help readers practice and improve OOP skills as well as review
the knowledge in previous chapters.
Chapter 11
File Processing....................................................................................................241
During software deployment, different kinds of file will be used depending on the
specific case. The book will show the series of four file types: Text File, Serialize
File, XML File, JSon File so that readers have more options in file processing.
Why does program have to store data? As computer architecture is mentioned, a
program wants to work, every resource must be loaded into memory, namely the
RAM (Random Access Memory). The principle of RAM is the clipboard, when
the software is turned off the data in the memory will no longer there. Assuming
customers are entering 100 products, and the power is suddenly cut, if there is no
mechanism to save data from RAM memory to the hard drive, customers will be
losing all the data. Kotlin uses JVM libraries to interact with the file, so programmers
can invoke these libraries. This chapter provides examples of handling saving and
reading files with different cases, which help readers to cover most of the processing
cases in practice. At the end of the chapter, there are exercises to improve readers
skills with file processing.
Chapter 12
Graphic User Interface........................................................................................305
Chapter 13
Vert.X for Kotlin Restful API.............................................................................394
Index................................................................................................................... 455
xiii
Preface
level of difficulty in order from low to high, so you should study each lesson
and we hope you will try your best to study Kotlin. Mastering Kotlin will
give readers invaluable chances in the future, because in the future there will
be a sin wave of recruiting Android programmers who are good at Kotlin.
With the desire to share knowledge about Kotlin programming language,
we published the book Principles, Policies, and Applications of Kotlin
Programming to provide comprehensive knowledge of Kotlin programming,
the book that introduces the benefits of Kotlin programming, core of Kotlin,
how to use programming tools, data types and variables, conditional and
loop executions. Addition, the exception handling, important libraries
commonly, string processing, array and collection processing are explained
in the book. Especially knowledge of Object Oriented Programming in
Kotlin, file processing, graphic user interface and Vert.X for Kotlin Restful
API also implemented. Readers will gain a sufficient amount of knowledge
about Kotlin to be able to continue implementing real projects, which can
be applied to Restful API programming as well as Android programming.
Here are the main summaries of Kotlin programming knowledge presented
in the 13 chapters that we cover in this book.
xiv
Preface
When dealing with list data such as character strings, numeric arrays, list of
objects, etc. then loops will be used. Kotlin provides loop controls such as
for, while, do while and abnormal loop termination. The loop executions are
greatly improved, such as for loops that are divided many types such as closed
range, half-open range, step and downTo navigation. And these kinds cover
most of the loop handling cases, making it easy for programmers to use them
optimally. This chapter also demonstrates how to handle break statement and
continue statement in abnormal loop termination, these are very important
statements in loop handling. This chapter also provides complete code and
detailed explanations for each loop, making it easy for learners to understand
and practice loops.
xv
Preface
Every programming language has a set of libraries that will help programmers
quickly solve certain tasks, and programmers must certainly use it because
programmers cannot write some libraries or it spends long time, so
programmers must know how to use it. These libraries may be in the JVM or
KotlinJavaRuntime or in any other external library: Numeric Data Processing
Library, Date processing library, Math processing library, Random number
processing library, String processing library.
Array is one of the very important data in software processing, it will be used
to store data in the form of a list. Almost programming languages support
array processing, and so does the Kotlin language. However, with Kotlin,
arrays are a very powerful data type, which overcomes many disadvantages
compared to other programming languages such as C++, C#, Java, etc. In
chapter data type, the book has briefly mentioned some of the array types that
are built-in in Kotlin, such as: CharArray, BooleanArray, IntArray, FloatArray,
DoubleArray, etc. The book also presents multiple-array with IntArray type.
Chapter 9. Collections
Arrays do not meet and difficult to implement, because the data usually has
no change in quantity, no deleting or changing the position of data, then it
is appropriate to use an array, but when it comes to cases where the data
changes continuously, or the number of elements is not known in advance, or
the position in the list can be shuffled, using arrays is no longer optimal, so
collections are more optimal. This chapter presents hierarchical collections
xvi
Preface
xvii
Preface
like List, Table, Tree, etc. For each type of control, detailed instructions and
instructions are provided, which makes it easy for readers to grasp the theory
and implement the practical parts.
Jun-Ho Huh
Korea Maritime and Ocean University, South Korea
xviii
xix
Acknowledgment
Chapter 1
Introducing Kotlin
Programming Language
ABSTRACT
This chapter introduces Kotlin programming language and its strengths,
such as brevity, saftey, versatility, and interoperability features. Readers will
discover how to install Kotlin programming tools, how to create projects,
program sample projects and check the output results. At the same time, this
chapter also presents the types of notes when programming such as single-line
comment, multi-line comments, and KDoc comments; comments are one of
the important requirements of the software industry. Readers will be familiar
with simple and easy-to-understand examples so that readers can practice
after reading and using the functions in the IntelliJ IDEA programming tool.
Finally, there are exercises listed at the end of the chapter to help readers
practice more programming skills with Kotlin.
KOTLIN INTRODUCTION
DOI: 10.4018/978-1-6684-6687-2.ch001
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Introducing Kotlin Programming Language
Recently, the name Kotlin has created on May 17, 2012, and Google has
announced that Kotlin will become the official Android programming
language in 2017. From Android version 3.0, developers can use this language
(Jemerov et al., 2017).
The table below shows a summary of the official Kotlin versions published
over the years.
2
Introducing Kotlin Programming Language
3
Introducing Kotlin Programming Language
• We can easily write the POJO (Plain Old Java Object) on one line:
4
Introducing Kotlin Programming Language
object ThisIsASingleton {
var Name: String = “Viking”
}
In addition, there are many more brief programming styles; you take a
quick look at https://kotlinlang.org/.
How safe is it?
Kotlin automatically checks for Null pointer exception, the actions on the
null data set, and automatically casts the correct type for us, for example.
KOTLIN JAVA
var s1:String?=null
//does not run String s1=null;
//kotlin check s1 is null so method not executed //runs and through exception
s1?.trim() //java doesn’t check s1 is null or not
s1=”Hello World” s1.trim();
//does runs, because s1 is not null s1=”Hello World”;
s1?.trim() //runs method, because s1 is not null
//runs anyway (don’t care s1 is null or not null) s1.trim();
s1!!.trim() String s2=”I’m Java”;
var s2:String=”I’m Kotlin” //runs method, because s2 is not null
//no need s2? because String instead String? s2.trim();
s2.trim()
5
Introducing Kotlin Programming Language
In previous lesson, the book showed why you should study Kotlin. In this
lesson, we will learn how to install the Kotlin programming tool.
To program Kotlin, you can use the Website to test online https://try.
kotlinlang.org/
Alternatively, install IntelliJ IDEA, Eclipse Neon, Command Line Compiler,
Build Tools (Ant, Maven, Gradle, Griffon (external support)).
In this lesson, we will show you how to install the IntelliJ IDEA software
for Kotlin programming (because throughout the Kotlin programming tutorials,
we will use this tool for illustration.)
First, you need to install JDK on your computer (Kotlin running on the
JVM, install 1.8 or higher version); Kotlin course is usually for those who
are already familiar with Java. Please take this step yourselves.
You download the Community version of IntelliJ IDEA at the following
link: https://www.jetbrains.com/idea/download
6
Introducing Kotlin Programming Language
We see that the current version of the file “ideaIC-2021.1.3.exe” has more
than 659 MB. To install, double click on the downloaded file:
Click Next to continue, the screen asking where to install will display as
below:
7
Introducing Kotlin Programming Language
We can choose the default mode and then click Next, the program will
display the configuration to be selected during the installation process, select
the configuration as above and click next, the installation Options screen
appears as below.
8
Introducing Kotlin Programming Language
Checked the options as the same screen above and then click Next. Screen
required to select Start Menu appears:
9
Introducing Kotlin Programming Language
You choose the default mode and then click Install, wait for the program
to complete the installation:
10
Introducing Kotlin Programming Language
Figure 9. Installing
11
Introducing Kotlin Programming Language
Choose Reboot now and click Finish to complete the installation. In the
desktop screen, click on icon “IntelliJ IDEA Community Edition” to run the
software. If you are running the software for the first time, you will encounter
the following window:
12
Introducing Kotlin Programming Language
We choose “Do not import settings” and then click OK, the screen asking
for the Theme setting the tool appears:
13
Introducing Kotlin Programming Language
There are three color themes, depending on your choice, then click Skip
All and Set Defaults for quick process, below is the screen after you have
configured IntelliJ IDEA, the Welcome Screen will be similar:
As for now, the book has completed the instructions on how to download
and install the Kotlin programming tool, if you have ever done the Android
Studio, is the interface very similar?
In the next lesson, the book will show how to create a project HelloWorld
Kotlin, to feel programming in this new language. Please pay proper attention
to the tutorial.
14
Introducing Kotlin Programming Language
Before we go into details about Kotlin, you need to know how to create the
first Project Kotlin, we often say in English that it is “Hello World Project”.
Launch IntelliJ IDEA, from the short cut on the desktop, double click to launch:
15
Introducing Kotlin Programming Language
After clicking Create New Project, the New Project screen appears:
16
Introducing Kotlin Programming Language
On the New Project screen above, you need to set Project SDK. This is
where you select the path where you installed the JDK, click combobox to
point to where you have installed (you should install JDK from 1.8 or higher
version). Project name is “HelloWorld”, language “Kotlin”, build system
“IntelliJ” and choose location to store, then click Finish.
Here is the screenshot of Project Kotlin created:
17
Introducing Kotlin Programming Language
18
Introducing Kotlin Programming Language
o The “src” directory is where the source code files are stored for the project.
19
Introducing Kotlin Programming Language
Name: You can set the name as you wish, for example, we choose the name
App.
Kind: Select File (this will select File; the following lesson will be the case
where we select other types in the combo box).
Press Enter to create; we will see the source code structure as follows:
20
Introducing Kotlin Programming Language
So, you see, the extension of Kotlin is kt, we proceed to Coding to export
the outstanding message “Hello World! I am Kotlin”:
In the coding editor of App. kt, just type main (main method without
parameter) or maina (main method with parameter) and press ctrl + space,
the full main function will appear:
When you press Ctrl + space, you see the blue line above appears with
the main () function ==> you just need to press Enter, it will automatically
appear full command (this is called Template, you can configure yourself,
and there are many IntelliJ IDEA default templates):
21
Introducing Kotlin Programming Language
You have seen the main Function structure, with the fun keyword (i.e.,
function), and with arguments input inside run when the code is run (often
used to pass call parameters between different applications). If you want to
export the command prompt to the screen then write inside the main function,
for example:
In what aspects is this different from Java? Finalizing the statement without
a semicolon, isn’t it? Now how can we run this command? You can go to
Run / Run menu. Alternatively, right-click on App.kt and select Run App.
kt as shown below:
22
Introducing Kotlin Programming Language
You wait for the program to compile and you will have the output as below:
23
Introducing Kotlin Programming Language
We have shown you how to create a first Project Kotlin, as well as how to
run it, you need to do this to master the basic operations first.
You can download the source code here to test: https://github.com/
thanhtd32/kotlin/tree/main/HelloWorld
println(“Sun”)
println(“Earth”)
println(“Moon”)
Sun
Earth
Moon
The print() function is used to export data on the same line, for example:
print(“Sun”)
print(“Earth”)
print(“Moon”)
SunEarthMoon
• \n to begin a newline
• \t for indentation
24
Introducing Kotlin Programming Language
• \” to quote
Listing 1. LearnSpecialCharacter/App.kt
It sits, poisonous
Dripping sorrow over the windowsill
I drove to the “Skyway”
Dropped a heart over the edge.
Watched it splash under
It took a couple seconds to hit.
The book has shown how to print strings to the screen, please practice two
functions print() and println(). Download source code here:
https://github.com/thanhtd32/kotlin/tree/main/LearnSpecialCh
aracter
Comments
25
Introducing Kotlin Programming Language
Listing 2. LearnComments/App_Comment1Line.kt
You see line number 2 has string // call plus function for 2 numbers =>
this is the comment line. This syntax allows us to comment a line, based on
this we can understand what the command below is used for.
/* Comment line 1
Comment line 2
Comment line n
*/
26
Introducing Kotlin Programming Language
Allow you to make comments on different lines, the Listing 3 shows the example.
Listing 3. LearnComments/App_CommentMultipleLine.kt
1 /*
2 This is the main function
3 used to run the program
4 */
5 fun main(args: Array<String>) {
6 //call plus function for 2 numbers:
7 var t:Int=7.plus(8)
8 println(t)
9 }
We look at the top of the main function with multiple line comments to
explain in detail a command, a block of command or a function (depending
on our purpose and style).
27
Introducing Kotlin Programming Language
Listing 4. LearnComments/App_CommentKDoc.kt
1 /**
2 * @author Tran Duy Thanh
3 * @param x parameter x
4 * @param y parameter y
5 * @return sum of x and y
6 * @sample x=5, y=6 => 11
7 * This is docs comment
8 */
9 fun Plus(x:Int,y:Int):Int
10 {
11 return x+y
12 }
13 /*
14 This is the main function
15 used to run the program
16 */
17 fun main(args: Array<String>) {
18 //call plus 2 numbers function
19 val t:Int=Plus(7,8)
20 println(t)
21 }
The way to write notes in KDoc format is very convenient, when using the
function, we only need to move the mouse to know the function description,
the meaning of the function as well as the arguments in the function. This helps
programmers easily understand how to use the function quickly, optimizing
time and effort to learn.
The following figure shows at command line 19, we move the mouse to
the Plus function, the usage description of this function will be displayed
as below:
28
Introducing Kotlin Programming Language
Exercises
29
Introducing Kotlin Programming Language
REFERENCES
30
31
Chapter 2
Data Types and Variables
ABSTRACT
In the process of programming, understanding data types and variable
declaration plays an important role in software development. When choosing
the right data type and managing variables well, this will help the software to
be optimized and memory, making the customer experience for the software
better. The chapter will present the data types of the Kotlin language, data
types will be grouped some category to make it easy for learners to remember
and compare, data explicit conversion and implicit conversion are mentioned.
Also, important operators for data types covered in this chapter include unary
operators, basic arithmetic, assignment, comparison, Logic, increment and
decrement operators, etc. This chapter also guides how to input data into
the software from the keyboard to help readers easily test the cases during
the programming process. For each content, this chapter provides simple
and easy-to-understand sample code for easy access, and at the end of the
chapter there are practice exercises to improve programming skills.
DOI: 10.4018/978-1-6684-6687-2.ch002
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Data Types and Variables
and compare, data explicit conversion and implicit conversion are mentioned.
Also, important operators for data types covered in this chapter include unary
operators, basic arithmetic, assignment, comparison, Logic, increment and
decrement operators, etc. This chapter also guides how to input data into the
software from the keyboard to help readers easily test the cases during the
programming process. For each content, this chapter provides simple and
easy-to-understand sample code for easy access, and at the end of the chapter
there are practice exercises to improve programming skills.
Data Types
Each programming language provides several types of data that are available
for storing. In addition, Kotlin offers a wide range of data types, such as real
numbers, integers, characters, strings, logic, and arrays. The fact is that all
types of data in Kotlin are object oriented. Understanding the meaning of
each type of data helps, we choose how to declare variables of the appropriate
type, which helps optimize the system.
Figure 1 shows overview of the built-in data types in Kotlin.
32
Data Types and Variables
Floating numbers will have two types, Double and Float. If there is a
constant to determine that it is a real number, then we can add the letter f or
F behind that constant:
For example: 113.5 → Double; 113.5F or 113.5f → Float
There are four types of integers: Long, Int, Short, Byte. Note the case of
the Long and Int constants by adding the letter L
For example: 113→ Int number; 113L → Long number
Listing 1. LearnDataType/App.kt
var c:Char=’c’
The string type used to store character sets is in double quotation strings,
using the String object to declare:
33
Data Types and Variables
Listing 2. LearnDataType/App_String.kt
Logical type uses a Boolean object to declare that this type of data will hold
true or false value, which is very important to use in conditional checking:
var result:Boolean=true
With array data types, Kotlin provides us with eight types of arrays for
eight data types built into Kotlin (except for String).
To declare and use the data type, please follow these steps:
With XXX is the corresponding 8 data types (the first character is usually
lowercase), Listing 3 show how to use the array data type.
Listing 3. LearnDataType/App_ArrayData.kt
34
Data Types and Variables
2
10.3
a
Listing 4. LearnDataType/App_constant.kt
We have presented the data types and how to declare variables in Kotlin,
you remember to do this again to understand more about data types in Kotlin,
you should compare the differences in data type as well as how to declare
variables to java.
Source code you can download at the link: https://github.com/thanhtd32/
kotlin/tree/main/LearnDataType.
35
Data Types and Variables
36
Data Types and Variables
Explicit Conversion
Listing 5. LearnDataConversion/App_Int_to_Double.kt
1
2 fun main(args: Array<String>) {
3 var X:Int=10
4 //Convert value of X from Int data type to Double data type
5 var D:Double=X.toDouble()
6 println(“X=”+X)
7 println(“D=”+D)
8 }
9
Listing 6. LearnDataConversion/App_Double_to_Int.kt
1
2 fun main(args: Array<String>) {
3 var F:Double=10.5
4 //Convert value of F from Double data type to Int data type
5 var Y:Int = F.toInt()
6 println(“F=”+F)
7 println(“Y=”+Y)
8 }
9
The result of F = 10.5 and Y = 10. In this case, we loss the data, this is
the case of narrowing, taken from the conversion, which has a larger storage
areaon the data conversion which has smaller storage area. Narrowing is
very dangerous because it causes data loss, especially problems related to
minimum requirements, or bank transfer. This should be avoided.
37
Data Types and Variables
Implicit Conversion
Kotlin also supports one case of Implicit Conversion, Kotlin interprets the data
conversion to assign variables, usually by arithmetic operations, for example:
var t=13L+1
println(t)
Listing 7. LearnDataConversion/App_ImplicitConversion.kt
Unlike the Java language, Kotlin does not allow assignments or operations
with incorrect numeric data types. With Kotlin we have to implement the
correct data type. In command line number 4, calling d=x+1 will give an error
because x and number 1 are of type Int and d is of type Double. However,
we can adjust d=x+1.0, now 1.0 has a Double and it automatically converts
x to Double to perform the math.
We have presented how to converse data in Kotlin, this lesson is very
important. We need to make sure that the conversion rule is chosen properly.
And certainly, in the programming process we must encounter frequent cases
of conversing.
You can download the Source code at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnDataConve
rsion.
Important Operators
38
Data Types and Variables
these operators are also used by Kotlin Overrides as methods. (We can use
pure operators and also by using methods.)
• Unary operators
• Basic arithmetic operators
• Assignment operators
• Comparison Operators
• Logic operators
• Increment and Decrement Operators
• Operator precedence:
Unary Operators
Listing 8. LearnImportantOperators/App_Unary_Operators.kt
39
Data Types and Variables
a=-8
b=-8
c=8
Note that unaryPlus and unaryMinus do not change the internal value of
the variable, but it returns a value, which requires a variable to store this value.
Like other programming languages, Kotlin also supports the basic arithmetic
operators shown in Table 2.
The examples for basic arithmetic operators are shown in the Listing 9.
Listing 9. LearnImportantOperators/App_Basic_Arithmetic_Operators.kt
1
fun main(args: Array<String>) {
2
var a:Int=8
3
var b:Int=5
4
println(“Plus method 1:”+a+”+”+b+”=”+(a+b))
5
println(“Plus method 2:”+a+”+”+b+”=”+(a.plus(b)))
6
println(“Minus method 1:”+a+”-”+b+”=”+(a-b))
7
println(“Minus method 2:”+a+”-”+b+”=”+(a.minus(b)))
8
println(“Multiply method 1:”+a+”*”+b+”=”+(a*b))
9
println(“Multiply method 2:”+a+”*”+b+”=”+(a.times(b)))
10
println(“Divide method 1:”+a+”/”+b+”=”+(a/b))
11
println(“Divide method 2:”+a+”/”+b+”=”+(a.div(b)))
12
println(“Find remainders method 1:”+a+”%”+b+”=”+(a%b))
13
println(“Find remainders method 2:”+a+”/”+b+”=”+(a.rem(b)))
14
println(8.plus(9))
15
}
16
40
Data Types and Variables
Assignment Operators
41
Data Types and Variables
x=7
x=5
x=10
x=5
x=1
Comparison Operators
Kotlin language supports comparison operators, they are shown in the Table 4.
42
Data Types and Variables
a.equals(b) returns true if a and b are equal, false if a and b are different.
a.compareTo(b) returns 0 if a and b are equal, returns >0 if a>b, and
returns <0 if a<b.
Running the above code, we will have the following results
false
false
true
1
0
-1
1
Logic Operators
Kotlin support logic operators && and ||, the details are shown in the Table 5.
43
Data Types and Variables
x=true
y=false
z=false
x&&y=false
x.and(y)=false
x || y =true
x.or(y)=true
x || z =true
x.or(z)=true
x && z =false
x.and(z)=false
y || z =false
y.or(z)=false
y && z =false
y.and(z)=false
x && y && z =false
x.and(y).and(z)=false
x|| y||z =true
x.or(y).or(z)=true
44
Data Types and Variables
45
Data Types and Variables
Running the above code, we will have the following results as the same
we explained:
a=5
b=10
c=1
z=20
Operator Precedence
Kotlin has a constraint in the order precedence of the operators and it is shown
in the Table 7. However, it is best that you manipulate it by using parentheses
() to make it clearer. The table below refers to the priority from high to low
(however, please use the parentheses () to specify).
46
Data Types and Variables
We have given you a brief introduction about operators, please read it and
examples carefully.
Download source code here: https://github.com/thanhtd32/kotlin/tree/
main/LearnImportantOperators.
User Input
In this lesson, the book will show how to input data from the keyboard.
For Kotlin, to input data from the keyboard, we use the readLine() function,
which is located in the default library kotlin.io
The readLine () function will returns a string of data entered from the
keyboard or null if no data is available.
From this result string we can converse the data type of any type, we wish
to match the value entered.
47
Data Types and Variables
Welcome to!!!
Tran Duy Thanh
Did you notice that I have declared String? The data type is null able, which
is a new way of declaring it in Kotlin. It is the same for Int? and Double?, etc.
With some formatting in the Kotlin, we always pass the data type to the
original format. String in Kotlin is supported by a set of methods, it is shown
in the Table 8.
Coding example for converting string to numerics is shown in the Listing 15.
1
2
3
4 fun main(args: Array<String>) {
5 var x1:Boolean=”true”.toBoolean()
6 println(x1)
7 var x2:Byte=”3”.toByte()
8 println(x2)
9 var x3:Short=”30”.toShort()
10 println(x3)
11 var x4:Int=”15”.toInt()
12 println(x4)
13 var x5:Long=”100”.toLong()
14 println(x5)
15 var x6:Float=”15.5”.toFloat()
16 println(x6)
17 var x7:Double=”15.5”.toDouble()
18 println(x7)
19 }
20
21
22
48
Data Types and Variables
true
3
30
15
100
15.5
15.5
For example, write a program to solve the first-degree equation, this one
will apply the readLine () input from the key to solve the first-degree equation,
however the book will explain how the If and Else works in the next lesson,
Listing 16 shows details of the coding.
Running the above code, we will have the following results. Table 9 shows
some test cases.
49
Data Types and Variables
This is the end of the lesson. Please try to best to read the lesson and
examples.
Here is the link to download the code for this lesson: https://github.com/
thanhtd32/kotlin/tree/main/LearnInputData.
Knowledge about data types, how to declare variables, operators, readers
can learn more in the books by Dmitry Jemerov et al. (2017) and Dawn
Griffiths and David Griffiths (2019) and Andrew Bailey et al. (2021).
Exercises
var d:Double
d=10
var f:Float
f=9.5
50
Data Types and Variables
19. What are the results when run the following statements?
var a:Int=4
var b:Int=7
var c:Int=3
var z=a++ + ++b - --c + 2
println(“a=”+a)
println(“b=”+b)
println(“c=”+c)
println(“z=”+z)
Figure 3.
51
Data Types and Variables
◦◦ Where a is the length of the base side in the figure is side BC.
◦◦ h is the height from the top to the bottom edge, in the figure is AH.
24. ASCII character
Write a program to input a character: Print the ASCII code of that
character and prints its next character.
25. Write a program to reverse a positive integer exactly 3 digits, Eg: if we
Input a value is 456 then output is 654.
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021), Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Dmitry & Svetlana. (2017). Kotlin in Action. Manning.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
52
53
Chapter 3
Conditional Execution
ABSTRACT
Almost every programming language has to use conditional constructs to
handle the business of the software. Basically, the operating mechanism of
these conditional structures is the same, but with the Kotlin programming
language, it has added a lot of extended and very convenient features, it helps
programmers more optimal options in the process of processing business.
This chapter will present conditional constructs about simple if statement, if/
else statement, nested conditionals, expression and block form {}, and when
structure. The when structure has been greatly improved in Kotlin, it provides
a lot of use cases so that programmers can easily handle business tasks more
optimally, such as when with if/else statement, group multiple conditions.
For each conditional structure, this chapter provides simple examples and
detailed explanations to help readers understand the working mechanism
of the conditional structure and apply them to specific business handling.
At the end of the chapter, there is a list of exercises to help readers improve
programming skills on conditional structures.
CONDITIONAL EXECUTION
DOI: 10.4018/978-1-6684-6687-2.ch003
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Conditional Execution
This chapter will present conditional constructs about simple if statement, if/
else statement, nested conditionals, expression and block form {}, and when
structure. The when structure has been greatly improved in Kotlin, it provides
a lot of use cases so that programmers can easily handle business tasks more
optimally, such as when with if/ else statement, group multiple conditions.
For each conditional structure, this chapter provides simple examples and
detailed explanations to help readers understand the working mechanism
of the conditional structure and apply them to specific business handling.
At the end of the chapter, there is a list of exercises to help readers improve
programming skills on conditional structures.
if (<expression>)
{
<statement>
}
The “if” statement is only concerned with the correct condition, when
<expression> in “if” true, it will execute the <statement> statement inside
the “if”.
The Figure 1 shows the Flow Chart of if simple if statement.
54
Conditional Execution
Listing 1. LearnIfElse/App_If.kt
55
Conditional Execution
The above program code only checks the condition score>=65, command
at line 2 assigns score = 75.0, so the result will output “Pass”. If we change
the score=50.0, the program will not output any results.
if (<expression>)
{
<statement 1>
}
else
{
<statement 2>
}
The “if else” statement is concerned with true and false conditions. If
<expression> is true then the content <statement 1> of if will be executed, if
<expression> is false then the else statement <statement 2> will be executed.
This is one of the most commonly used statements in the conditional check
process.
Figure 2 shows the Flow Chart of the if/else statement.
56
Conditional Execution
Listing 2. LearnIfElse/App_IfElse.kt
57
Conditional Execution
The above program code only checks the condition score>=65, command
at line 2 assigns score = 75.0, so the result will output “Pass”. If we change
the score=50.0, the program will output “Fail”.
Nested Conditionals
In fact, when dealing with problems, we have to use many nested if else, with
many complex conditions.
We edit the example above: Enter the score in the range [0…100], if score
>=65, then output “Pass”. If score <= 65, then output “Fail”. And If user
enters the value is out of range [0…100] or nothing, then print incorrect
information. Listing 3 shows the details of the coding.
Listing 3. LearnIfElse/App_NestedIfElse.kt
58
Conditional Execution
Thus, we have already learned the “if else” approach by the traditional
method (as a conditional expression).
Now the book will present the new “if else” point in Kotlin that is it works
as an expression that returns the result. For example, if we have 2 numbers
a and b, how to find the largest number? Listing 4 shows the conditional
statement as expression.
In addition, the if else expression allows you to write in block form {}, the
last line in each block that returns the result, Listing 5 shows the coding.
59
Conditional Execution
Listing 5. LearnIfElse/App_BlockForm.kt
Choose b
max = 15
The value a at the end of if, the value b at the end of else is the result
returned and assigned to the max variable.
This is the end of the lesson, please pay attention to it through the examples
above. Take special note of the flow chart, the way of writing in the form
of the if else expression. Download source code here: https://github.com/
thanhtd32/kotlin/tree/main/LearnIfElse.
When Expression
For Kotlin, the “switch” expression was replaced by the “when” expression.
When operating very powerful, versatile, meet many processing cases for
programmers. Hopefully with 6 types of when in this lesson, it will help
you understand the operation of when, which can be applied smoothly to
the other more complex.
Syntax of when
when(<expression>)
{
<value 1> -> <statement 1>
<value 2> -> <statement 2>
<value 3> -> <statement 3>
<value …> -> <statement …>
<value n> -> <statement n>
else -> <statement else>
}
60
Conditional Execution
when statement will get the value in <expression>, compare it with the
<value> inside, if it matches any value, the <statement> will be executed.
If all <value> do not match <expression> then else will be executed. The
flowchart of when can be operated as shown in the Figure 3.
61
Conditional Execution
The simple when statement is shown in this example, we ask the user to
enter an integer value from 1→7, the program will output the corresponding
weekdays as follows.
Value Weekdays
1 Sunday
2 Monday
3 Tuesday
4 Wednesday
5 Thursday
6 Friday
7 Saturday
If value is out of [1…7] Invalid Value
Listing 6. LearnWhen/App_Example1.kt
1 fun main() {
2 var value:Int
3 println(“Please enter a value[1..7]:”)
4 value= readLine()!!.toInt()
5 when(value)
6 {
7 1 -> println(“Sunday”)
8 2 -> println(“Monday”)
9 3 -> println(“Tuesday”)
10 4 -> println(“Wednesday”)
11 5 -> println(“Thursday”)
12 6 -> println(“Friday”)
13 7 -> println(“Saturday”)
14 else -> println(“Invalid value”)
15 }
16 }
62
Conditional Execution
In the above test cases, we enter 4 programs that will output “Wednesday”,
enter 2 programs will output “Monday”, enter 9 programs will report the
error “Invalid value”.
Listing 7. LearnWhen/App_Example2.kt
63
64
Table 4. Test cases for corresponding operation
Input a: Input a:
3 3
Input b: Input b:
5 5
Enter operator(+,-,*,/): Enter operator(+,-,*,/):
+ -
3.0 + 5.0 = 8.0 3.0 - 5.0 = -2.0
Input a: Input a:
3 3
Input b: Input b:
5 5
Enter operator(+,-,*,/): Enter operator(+,-,*,/):
* /
3.0 * 5.0 = 15.0 3.0 / 5.0 = 0.6
Input a: Input a:
5 7
Run the coding and take some test cases.
Input b: Input b:
0 8
Enter operator(+,-,*,/): Enter operator(+,-,*,/):
/ ?
Denominator must be different from 0 Invalid operator
Conditional Execution
Conditional Execution
Listing 8. LearnWhen/App_Example3.kt
65
Conditional Execution
In the above program, we carry out some test cases such as February, May,
September, February. In addition, there is an invalid month that is month 13.
You can conduct tests on the remaining months.
The when Kotlin’s architecture is in, allowing for continuous data:
Kotlin language also uses “in” conditions in when expression to check if the
value is in the specified data group. Let’s observe how GPA and Letter Grade
are calculated based on the Table 6.
Use the when expression to calculate Letter Grade and GPA when the
Percentage is known, the Listing 9 shows full coding.
66
Conditional Execution
Listing 9. LearnWhen/App_Example4.kt
67
Conditional Execution
Also, when is an expression that returns results, the flexible way of writing
is shown in the Listing 10.
Run the program, we will have result=108 Because the above writing
assigns the result to the result variable, when x = 8 then the range 1...10, we
have the result = 8 + 100 = 108.
Similarly, you can try changing x=25, x = 40 to see how the result changes.
68
Conditional Execution
Finally, when can behave as an if-else expression, let’s see the Listing 11.
This is the end of the lesson, please pay attention to learn and understand
it through the examples above. Particularly grasp the flow chart, how to write
in different ways.
This is the link to download the source code of this lesson:
https://github.com/thanhtd32/kotlin/tree/main/LearnWhen
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017. Griffiths & Griffiths, 2019; Bailey et
al., 2021).
69
Conditional Execution
Exercises
1. What is the output to the screen when running the following commands?
var x: Int = 5
var y: Int = 6
if (x%2!=0 && y %2==0) {
println(“A”)
}
else{
println(“B”)
}
(a) A
(b) B
2. What is the output to the screen when running the following commands?
var x: Int = 5
var y: Int = 6
if (!(x%2!=0) && y %2==0) {
println(“A”)
}
else{
println(“B”)
}
(a) A
(b) B
3. What is the output to the screen when running the following commands?
var x: Int = 5
var y: Int = 6
var z:Int =8
if (z%y!=0) {
if(x>=y){
println(“A”)
}
else{
println(“C”)
}
}
else{
println(“B”)
}
70
Conditional Execution
(a) A
(b) B
(c) C
4. What is the output to the screen when running the following commands?
var a:Int=5
var s=if (a>7) “X” else if (a<=4) “Y” else “Z”
println(s)
(a) X
(b) Y
(c) Z
5. What is the output to the screen when running the following commands?
var a:Int=10
var b:Int=15
var c:Int=20
var z = if (a > b){
a
}
else if(b<c) {
b
}
else{
c
}
println(z)
(a) 10
(b) 15
(c) 20
6. Print digital clock. User enters any number of seconds t>=0. Calculate
and print the digital as folling format:
hour:minute:second AM or hour:minute:second PM
For example: If user enters the seconds are 3750, then print 1:2:30 AM.
If user enters the seconds are 51100, then print 2:11:40 PM
The calculation formula is as follows:
hour=(t/3600)%24
minute=(t%3600)/60
second=(t%3600)%60
71
Conditional Execution
var value=5
when(value%2)
{
0-> println(“X”)
1-> println(“Y”)
2-> println(“Z”)
}
(a) X
(b) Y
(c) Z
11. What is the output to the screen when running the following commands?
var value=5
when(value%2)
{
0,1-> println(“X”)
1,2-> println(“Y”)
0,2-> println(“Z”)
}
(a) X
(b) Y
(c) Z
(d) Compiler Error
12. What is the output to the screen when running the following commands?
var x:Int=15
var y:Int=5
var result=when(x/y)
{
in 1..2->x+y
in 3..7->x-y
else -> x
}
println(result)
72
Conditional Execution
(a) 20
(b) 10
(c) 15
13. Write a program to check the set of characters, The program description
is as follows:
Input: a character comes from the keyboard.
Check which of the following groups this character belongs to:
− Uppercase characters: ‘A’ ...’Z’
− Lowercase characters: ‘a’ ... ‘z’
− Alphanumeric characters: ‘0’ ... ‘9’
− Other characters.
14. Write a program to check hexadecimal numbers
The hexadecimal system uses 16 digits including the characters: 0, 1,
2, 3, 4, 5, 6, 7, 8, 9 and A, B, C, D, E, F. The characters A, B, C, D, E,
F have their respective values in the decimal system as follows:
73
Conditional Execution
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021), Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Dmitry & Svetlana. (2017). Kotlin in Action. Manning.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
74
75
Chapter 4
Loop Executions
ABSTRACT
Similar to the conditional structure, in all software, programmers have to
use loop structures to handle repetitive tasks according to certain rules.
When dealing with list data such as character strings, numeric arrays, list
of objects, etc. then loops will be used. Kotlin provides loop controls such
as for, while, do while and abnormal loop termination. The loop executions
are greatly improved, such as for loops that are divided many types such as
closed range, half-open range, step and downTo navigation. And these kinds
cover most of the loop handling cases, making it easy for programmers to
use them optimally. This chapter also demonstrates how to handle break
statement and continue statement in abnormal loop termination, these are very
important statements in loop handling. This chapter also provides complete
code and detailed explanations for each loop, making it easy for learners to
understand and practice loops. At the end of the chapter, there are exercises
to help readers practice programming skills for loops and consolidate the
knowledge in previous chapters.
LOOP EXECUTIONS
DOI: 10.4018/978-1-6684-6687-2.ch004
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Loop Executions
are greatly improved, such as for loops that are divided many types such as
closed range, half-open range, step and downTo navigation. And these kinds
cover most of the loop handling cases, making it easy for programmers to
use them optimally. This chapter also demonstrates how to handle break
statement and continue statement in abnormal loop termination, these are very
important statements in loop handling. This chapter also provides complete
code and detailed explanations for each loop, making it easy for learners to
understand and practice loops. At the end of the chapter, there are exercises
to help readers practice programming skills for loops and consolidate the
knowledge in previous chapters.
Kotlin provides about 5+ ways of working with a very wide range of “for”
loop. These techniques will detail you through theoretical as well as illustrative
illustrations, hopefully you will understand and master the For Loop in Kotlin.
The for – closed range, this way use to browse all the values in the list, the
syntax as below:
for (i in a..b)
{
Processing variable i
}
Listing 1. LearnFor/App_for_closed_range.kt
76
Loop Executions
for – half-open range - Browse almost all the values in the list, syntax as below:
for (i in a until b)
{
Processing variable i
}
77
Loop Executions
Listing 2. LearnFor/App_for_half_open_range.kt
for – step navigation use the step to iterate the value, syntax as below:
for (i in a .. b step x)
{
Processing variable i
}
78
Loop Executions
Listing 3. LearnFor/App_for_step_navigation.kt
1
fun main(args: Array<String>) {
2
var sum:Int=0
3
var n:Int=10
4
for (i in 2 .. n step 2)
5
sum+=i
6
println(“Sum of even numbers=$sum”)
7
}
8
for – downTo navigation, we use for loop with downTo keyword to increase
the variable when run for statement.
for (i in b downTo a)
{
Processing variable i
}
79
Loop Executions
Listing 4. LearnFor/App_for_downTo.kt
80
Loop Executions
To the 4th iteration, then both a and b are divisible by i (i = 3), so if the if
statement is executed, then gcd = 3 and the break command stops the loop.
Then command runs:
for – Set object loop, When we want to traverse each item in a collection,
the syntax is as follows:
81
Loop Executions
Listing 5. LearnFor/App_for_setobject1.kt
The above code, the program will browse each element in the book list
array and export their names.
Kotlin
Java
C#
Python
R
Also, we can browse by index, from this index we can export the output
the value as Listing 6.
Listing 6. LearnFor/App_for_setobject2.kt
The out:
Finally, the Kotlin language also supports both getting the index and the
value in the Listing 7.
82
Loop Executions
Listing 7. LearnFor/App_for_setobject3.kt
This is the end of the lesson, please pay attention to learn and understand
it through the examples above. Particularly grasp 5 ways of operation of for
to be able to apply well into actual projects.
You can download source code here: https://github.com/thanhtd32/kotlin/
tree/main/LearnFor.
In the previous lesson we learned how the for loop works, in this tutorial,
the book will explain the while loop excution. This is also one of the most
common repetition structures (loop) in any programming languages, the
syntax is as follows:
while(expression)
{
statement
}
83
Loop Executions
Note: The while statement may not be executed at all because the expression
does not match at the beginning. The Listing 8 shows the program to calculate
5 factorials.
84
Loop Executions
Listing 8. LearnWhile/App_Factorials.kt
Initialize n = 5, factorial = 1, i = 1
1st:
check i <= n ↔ 1 <= 5 (true) execute body white:
factorial = factorial*i=1*1=1
i++i=i+1=1+1=2
2nd:
check i <= n 2 <= 5 (true) execute body while:
factorial = factorial *i=1*2=2
i++i=i+1= 2+1=3
3rd:
check i <= n ↔3 <= 5 (true) execute body while:
factorial = factorial *i=2*3=6
i++i=i+1=3+1=4
4th:
check i <= n ↔ 4 <= 5 (true) execute body while:
factorial = factorial *i=6*4=24
i++i=i+1=4+1=5
5th:
check i <= n ↔ 5 <= 5 (true) execute body while:
factorial = factorial *i=24*5=120
i++i=i+1=5+1=6
6th:
check i <= n ↔ 6 <= 5 (false) stop while.
85
Loop Executions
do
{
statement
}
while(expression)
86
Loop Executions
Listing 9. LearnDoWhile/App_Example1.kt
87
Loop Executions
88
Loop Executions
Run the program and enter the following values to see the result, we can
repeat entering to test the values:
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. Particularly
grasp the way the operation of while loop to be able to apply well to his
actual project.
89
Loop Executions
The continue statement is similar to the break statement, except the continue
statement does not necessarily exit the loop. The continue statement skips
the rest of the body of the loop and immediately checks the loop’s condition.
Write a program to check whether a year is a leap year or not (leap year
is divisible by 4 but not divisible by 100 or divisible by 400). The program
requires users to enter the year> = 0, if entered incorrectly enter again until
the input is correct, the end of the program allows the user to choose whether
to continue or not. The Listing 11 shows the details of the code:
90
Loop Executions
Run the program and enter the following values to see the result:
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. Particularly
grasp the way of operating do…while to be able to apply well to your actual
projects.
The sourcode code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnDoWhileAb
normal.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel &
Isakova, 2020; Bailey et al., 2021).
Exercises
var n:Int=5
for (i in 1..n){
println(i)
}
91
Loop Executions
var n:Int=5
for (i in 1 until n){
println(i)
}
var n:Int=5
for (i in 2 .. n step 2){
println(i)
}
var n=5
for (i in n downTo 1){
println(i)
}
var n:Int=5
var s=0
for (i in 1..n){
if(i%2==0)
s=s+i
}
println(s)
92
Loop Executions
(a) 6
(b) 8
(c) 9
(d) 2
7. What is the output printed to the screen after executing the following
commands?
var n:Int=5
var s=0
for (i in 1..n){
if(i%2!=0)
s=s+i
}
println(s)
(a) 6
(b) 4
(c) 9
(d) 8
8. What is the output printed to the screen after executing the following
commands?
var n:Int=5
var s=0
for (i in 1 until n){
if(i%2==0)
continue
s=s+i
}
println(s)
(a) 2
(b) 4
(c) 1
(d) 8
9. What is the output printed to the screen after executing the following
commands?
var n:Int=5
var s=0
for (i in 1 until n){
if(i%2==0)
break
93
Loop Executions
s=s+i
}
println(s)
(a) 1
(b) 4
(c) 3
(d) 8
10. What Shape is drawn when the following commands are executed?
for (i in 1..5){
for (j in 1..5){
if(j==1 || j==5 || i==j)
print(“*”)
else
print(“ “)
}
println()
}
Figure 3.
11. What Shape is drawn when the following commands are executed?
for (i in 1..5){
for (j in 1..5){
if(j==1 || j==5 || i==5)
print(“*”)
else
print(“ “)
}
94
Loop Executions
println()
}
Figure 4.
12. What Shape is drawn when the following commands are executed?
for (i in 1..5){
for (j in 1..5){
if(j==1 || j==5 || i==1)
print(“*”)
else
print(“ “)
}
println()
}
Figure 5.
95
Loop Executions
13. What is the output printed to the screen after executing the following
commands?
var n:Int=5
var i:Int = 1
var s:Int=0
while (i <= n){
s=s+i
i++
if(i==3)
continue
}
println(s)
(a) 4
(b) 15
(c) 3
(d) 9
14. What is the output printed to the screen after executing the following
commands?
var n:Int=5
var i:Int = 1
var s:Int=0
while (i <= n){
s=s+i
i++
if(i==3)
break
}
println(s)
(a) 2
(b) 15
(c) 3
(d) 7
15. What is the output printed to the screen after executing the following
commands?
var n:Int = 5
var s:Int=1
var i:Int = 1
do{
s=s+i
96
Loop Executions
i=i+2
}while (i<=n)
println(s)
(a) 4
(b) 10
(c) 3
(d) 7
16. What is the output printed to the screen after executing the following
commands?
var n:Int = 5
var s:Int=1
var i:Int = 0
do{
s=s+i
i=i+2
}while (i<=n)
println(s)
(a) 7
(b) 10
(c) 9
(d) 5
17. Write a program to enter n>0 and calculate the expression S(n)
1 1 1
S (n ) = 1 + + +…+
3 5 2n + 1
1 1 1
S (n ) = 1 + + +…+
3 5 2n + 1
97
Loop Executions
multiplication table and asks the player to guess it within a set time. If
the player hits it within the specified time, it is counted as the correct
number, and if the calculation is incorrect or exceeds the time, it is
regarded as invalid. Also, for the difficulty of multiplication tables, the
2nd and 5th stages are excluded.
22. Multiplication table game machine (more level)
It was found that there were cases of asking the same multiplication table
while playing the game. Let’s modify it to eliminate the case of asking
for the same multiplication table. Also, if you do not answer within a
limited time, try to correct it so that it is regarded as wrong.
Readers modified the code in Exercise 21:
◦◦ Check duplication random number for multiplication
◦◦ Update the limit time about 45 second, if user answered the
product is over limit time, program will set wrong answer.
98
Loop Executions
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Dmitry & Svetlana. (2017). Kotlin in Action. Manning.
Eckel & Isakova. (2020). Atomic Kotlin. Mindview LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
99
100
Chapter 5
Exception Handling
ABSTRACT
In the process of programming, most of mistakes can be raised. And making
errors while programming is inevitable. Therefore, programmers need to
have ways to distinguish the types of errors and how to handle errors. This
chapter will present error levels such as compiler error, runtime exception
error, and exception logic error. This chapter also provides techniques for
catching errors such as try catch structure and throw exception technique.
Illustrative codes are presented for how to handle this error for readers to easily
grasp. However, most programming tools support debugging functions, and
this tool makes it easy for programmers to find errors and from there it helps
programmers easily find the solutions to fix errors quickly and accurately, so
this chapter presents IntelliJ IDEA’s debugging tool. At the end of the chapter
there are exercises to help readers improve the skills in exception handling.
EXCEPTION HANDLING
DOI: 10.4018/978-1-6684-6687-2.ch005
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Exception Handling
to know how to use it, this tool makes it easy for programmers to find errors
and from there it helps programmers easily find the solutions to fix errors
quickly and accurately, so this chapter presents IntelliJ IDEA’s debugging
tool. At the end of the chapter there are exercises to help readers improve
the skills in exception handling.
In the process of executing the software, there will be errors in the coding
process that have been predicted or unpredictable.
Controlling exceptions helps the software continue to work if an error
occurs or also prompts the User Problem.
When programming, we normally encounter three levels of error:
And when there are errors, there are usually two behaviors with errors:
Unchecked error and Checked error.
For professional programmer, we need to take care of these errors, to
check carefully so that when the error occurs, the program will continue
without being turned off.
101
Exception Handling
try
{
// write the commands here and these commands are those likely to generate errors
}
catch (e: SomeException)
{
// error handler here -> Detailed error message to know what is wrong to fix
}
finally
{
// optional finally block – Regardless of whether or not the error occurred, the block is always executed
}
The Listing 5.1 we write a program dividing two numbers a and b. For sample
denominator = 0 to generate error.
Listing 1. LearnException/App_Example1.kt
1
fun main(args: Array<String>) {
2
try {
3
var a:Int=5
4
var b:Int=0
5
var c=a/b
6
println(“$a/$b=$c”)
7
}
8
catch (e:Exception)
9
{
10
println(e.message)
11
}
12
finally {
13
println(“This is finally, 100% running, whether errors exist or not”)
14
}
15
}
16
When running the above program, the line a / b will generate an error and
it will jump to the exception, then finally will be executed:
/ by zero
This is finally, 100% running, whether errors exist or not
102
Exception Handling
Kotlin also supports the throw keyword to throw this error elsewhere, where it
calls it to handle the error. The Listing 2 shows how to use the throw keyword.
Listing 2. LearnException/App_Example2.kt
1 fun divide(a:Int,b:Int):Int
2 {
3 if(b==0)
4 throw Exception(“Denominator =0”)
5 return a/b
6 }
7 fun main(args: Array<String>) {
8 divide(5,0)
9 println(“Good Bye!”)
10 }
In the Listing 3, we modify the above code so that when the error occurs,
the program will continue to operate.
Listing 3. LearnException/App_Example2.kt
1
fun divide(a:Int,b:Int):Int
2
{
3
if(b==0)
4
throw Exception(“Denominator =0”)
5
return a/b
6
}
7
fun main(args: Array<String>) {
8
try {
9
divide(5, 0)
10
}
11
catch (e:Exception)
12
{
13
println(e.message)
14
}
15
println(“Good Bye!”)
16
}
17
103
Exception Handling
When try ... catch, despite the error, the program will continue to execute
the remaining commands (avoid turning off the software), the program on
the run will have the result:
Denominator =0
Good Bye!
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. Especially
understand how the operation of try…catch...finally ... throw to be able to
apply well to actual projects.
The source code can be downloaded at the link: https://github.com/
thanhtd32/kotlin/tree/main/LearnException.
In this lesson, the book will show how to handle exceptions to control bugs
in the runtime process However, in order to fix every step that the program
performs to find difficult errors such as Logic errors, we must use the Debug
tool, IntelliJ IDEA software has a built-in Debug tool to help us easily fix.
According to our experience, we have to spend more time fixing bugs
than writing new code.
With any Debug tool, we usually have three main operations:
Now the book will go into details of each operation in the IntelliJ IDEA
tool for you to Debug, assuming we have a command to solve the second-
degree equation in the Listing 4 (we are intentionally wrong in logic), our
task is to find out the logic errors by using the Debug tool:
104
Exception Handling
Listing 4. LearnDebugTool/App_Second_Degree_Equation.kt
Looking at the command above, have you found any logic errors?
We have 2 cases to test the Logic error above as follows
Case 1: 0x2+5x+2=0 1.
If true then the result should be x = -0.4, but when run up the result is x
= -2.5. This is the first wrong logic.
2.Case 2: x2+5x-6 =0
105
Exception Handling
If it is true then the result would be: x1=-6, x2= 1. But the result above
is x1 = -1.0, x2 = 6.0 here is the second Logic error
So how to debug it? Usually, we have to Debug in each line to test (of
course, we will hard encounter such trivial algorithms in reality, here is just
the typical example of solving the second order equation to who you the
debugging method).
Now we go into the details:
Step 1: To stop checking the command at any point, make a break point in
that line (this step is called set Break Point):
For example, if you want to set Break Point at command line 19 and the
command line 33 then click next to the number of lines where the red
arrow points to it, it will appear as a dot of that color, want to remove
it then Press again:
106
Exception Handling
When a line with a red dot appears, the breakpoint is set successfully.
Step 2: Run Debug in each line
Go to the Run menu / select Debug App_debug.kt (which is the file that
we wrote the main command to Debug)
The program executes and we enter the values for the variables:
107
Exception Handling
At the top of the screen, we can see the value of the variables right in
the debug line.
And the tool in Debug mode allows you to use the keys F7, F8, F9 to
navigate the Debug process:
108
Exception Handling
109
Exception Handling
After selecting Add to Watches -> this variable will be displayed in the
Variables screen:
110
Exception Handling
Because of the Logic error, we know the result is certainly wrong, and
we need to fix the command (in fact it is much harder, sometimes you
have to F7, F8 all day, and you still don’t find the bugs).
Similarly, you test the second case that if have two distinct false solutions.
This is the end of the lesson, please pay attention to the examples above
and do extra research to have a better understanding of the lesson. You need
to master Debug Tools, debug keys as well as Add to Watches to apply to
your actual projects.
You can download the wrong source code for this lesson here: https://
github.com/thanhtd32/kotlin/tree/main/LearnDebugTool.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel &
Isakova. 2020; Bailey et al., 2021).
111
Exception Handling
Exercises
112
Exception Handling
Point Result
60→100 Pass
<60 Fail
113
Exception Handling
114
Exception Handling
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Dmitry & Svetlana. (2017). Kotlin in Action. Manning.
Eckel &Isakova. (2020). Atomic Kotlin. Mindview LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
115
116
Chapter 6
Commonly Important Libraries
ABSTRACT
Every programming language has a set of libraries that will help programmers
quickly solve certain tasks, and programmers must certainly use it because
programmers either cannot write some libraries or it takes a long time; so
programmers must know how to use them. These libraries may be in the JVM
or KotlinJavaRuntime or in any other external library. In this chapter, the book
will present some commonly used libraries, such as numeric data processing
library, date processing library, math processing library, random number
processing library, and string processing library. And there are many other
processing libraries—readers can do more research about those libraries. At
the end of the chapter there are exercises to help readers improve the skills
in important libraries commonly.
Every programming language has a set of libraries that will help programmers
quickly solve certain tasks, and programmers must certainly use it because
programmers cannot write some libraries or it spends long time, so
programmers must know how to use it. These libraries may be in the JVM
or KotlinJavaRuntime or in any other external library:
DOI: 10.4018/978-1-6684-6687-2.ch006
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Commonly Important Libraries
Figure 1. KotlinJavaRuntime
In this chapter, the book will present some commonly used libraries
And there are many other processing libraries, readers can more research
about those libraries. At the end of the chapter there are exercises to help
readers improve the skills in important libraries commonly.
To format decimal digits for real numbers, you can use the following format,
syntax “%.nf” with n is the number of decimals to format, The Listing 1
shows how to use the decimal format.
Listing 1. LearnLibrariesCommonly/App_NumericFormat.kt
117
Commonly Important Libraries
3.3333333333333335
3.33
Listing 2. LearnLibrariesCommonly/App_DecimalFormat.kt
1
import java.text.DecimalFormat
2
import java.text.DecimalFormatSymbols
3
import java.util.Locale
4
fun main(args: Array<String>) {
5
var x:Int=986553823
6
var dcf=DecimalFormat(“#,###”)
7
var dcfs= DecimalFormatSymbols(Locale.getDefault())
8
dcfs.groupingSeparator=’,’
9
dcf.decimalFormatSymbols=dcfs
10
println(x)
11
println(dcf.format(x))
12
}
13
986553823
986,553,823
Notice the import command above is IntelliJ IDEA itself, just type Control
+ Space when using the library, it will automatically appear. Kotlin makes
it easy to invoke libraries in the JVM to help Java programmers to switch
languages.
When dealing with the day of the year we usually use 3 libraries:
• Date
• Calendar
118
Commonly Important Libraries
• SimpleDateFormat
import java.util.Date
import java.util.Calendar
import java.text.SimpleDateFormat
◦◦ Get current date:
var cal=Calendar.getInstance()
◦◦ Take each criterion
var year=cal.get(Calendar.YEAR)
var month=cal.get(Calendar.MONTH)
var day=cal.get(Calendar.DAY_OF_MONTH)
◦◦ Change the date parameter:
cal.set(Calendar.YEAR, 1990);
cal.set(Calendar.MONTH,2)
cal.set(Calendar.DAY_OF_MONTH,20)
◦◦ Get Date object:
var date=cal.time
◦◦ Format date as dd/MM/YYYY
var date=cal.time
var sdf=SimpleDateFormat(“dd/MM/yyyy”);
println(sdf.format(date))
Year=2021
Month=7
Day=16
16/08/2021
16/08/2021 03:36:51 PM
Note month is always running from 0-> 11, so when the number 4 is May
(we can see SimpleDateFormat output month).
hh:mm:ss aaa is the hour format: minutes: seconds, aaa is AM or PM. If
you want to format 24h to replace hh to HH
119
Commonly Important Libraries
Listing 3. LearnLibrariesCommonly/App_DateFormat.kt
1 import java.util.Date
2 import java.util.Calendar
3 import java.text.SimpleDateFormat
4 fun main(args: Array<String>) {
5 //Get the Calendar object (current date)
6 var cal:Calendar=Calendar.getInstance()
7 //Get year from cal object
8 var year:Int=cal.get(Calendar.YEAR)
9 //Get month from cal object
10 var month:Int=cal.get(Calendar.MONTH)
11 //Get day of the month from cal object
12 var day:Int=cal.get(Calendar.DAY_OF_MONTH)
13 println(“Year=$year”)
14 println(“Month=$month”)
15 println(“Day=$day”)
16 //Get DateTime from cal object
17 var date:Date=cal.time
18 //Create SimpleDateFormat object
19 var sdf=SimpleDateFormat(“dd/MM/yyyy”)
20 //print date with format
21 println(sdf.format(date))
22 var sdf2=SimpleDateFormat(“dd/MM/yyyy hh:mm:ss aaa”)
23 println(sdf2.format(date))
24 }
25
26
For math processing we use the Math library contained in the java.lang package.
Some common Math methods is shown in the Table 1.
120
Commonly Important Libraries
The example for math library, the coding is shown in the Listing 4.
Listing 4. LearnLibrariesCommonly/App_Math.kt
PI number=3.141592653589793
Absolute value of -4=4
number 9 is greater number
Square root of 25=5.0
3 power of 4 =81.0
sin(45)=0.7071067811865475
cos(45)=0.7071067811865476
tan(45)=0.9999999999999999
cotan(45)=1.0000000000000002
To deal with random numbers we use the Random class in the import java.
util. Random package
var rd=Random()
var x=rd.nextInt(n);
121
Commonly Important Libraries
For example:
Example:
Write the game “Guess the number”. The computer will issue a random
number [0...100], requiring the player to guess this number, allowing for 7
wrong guesses (more than 7 times the game over). If player guessed wrong,
let the player know that the number of player’s guess is smaller or larger than
the number of players.
And after the game ends (WIN or LOST). Program should ask if the player
wants to play again. The source code is shown in the Listing 5.
122
Commonly Important Libraries
Listing 5. LearnLibrariesCommonly/App_Random.kt
1 import java.util.Random
2 fun main(args: Array<String>) {
3 while (true) {
4 play()
5 println(“Do you want to play again?(y/n):”)
6 val tl = readLine()
7 if (tl.equals(“n”, ignoreCase = true))
8 break
9 }
10 println(“Good bye!”)
11 }
12 fun play()
13 {
14 var rd = Random()
15 var numberofProgram = rd.nextInt(101)
16 println(“Program picked a value in [0...100] Please guess!”)
17 var numberofPeople: Int=0
18 var numberofGuesses = 0
19 do {
20 println(“What number do you guess?:”)
21 var s=readLine()
22 if(s!=null)
23 numberofPeople = s.toInt()
24 numberofGuesses++
25 println(“You guess the $numberofGuesses times”)
26 if (numberofPeople == numberofProgram) {
27 println(“Congratulations!!!”)
28 println(“You are right!!”)
29 println(“Number of program is $numberofProgram”)
30 break
31 }
32 if (numberofPeople < numberofProgram) {
33 println(“You are wrong!!!”)
34 println(“Number of program> your number”)
35 } else {
36 println(“You are wrong!!!”)
37 println(“Number of program<your number”)
38 }
39 if (numberofGuesses == 7) {
40 println(“You are Game Over!!!”)
41 println(“Because you are wrong 7 times!”)
42 break
43 }
44 } while (numberofGuesses <= 7)
45 }
46
47
48
49
123
Commonly Important Libraries
124
Commonly Important Libraries
Listing 6. LearnLibrariesCommonly/App_StringBuilder.kt
Hello Kotlin
Hello Kotlin Language
Say Hello Kotlin Language
Say Kotlin Language
egaugnaL niltoK yaS
125
Commonly Important Libraries
Especially when concatenated as read from File, read from internet with
long content, we should use StringBuilder to append instead of +. Because
the use of the + sign of processing speed will be very slow.
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. Especially
understand how the libraries work to be able to apply well to actual projects.
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnLibraries
Commonly.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017. Griffiths & Griffiths, 2019; Eckel &
Isakova, 2020; Bailey et al., 2021).
Exercises
1. What is the output to the screen when running the following commands?
var a=5
var b=3
var c:Double=(a+b)/3.0
println(“%.2f”.format(c))
(a) 2.67
(b) 2.66
(c) 2.70
2. What is the output to the screen when running the following commands?
var x:Int=1000000
var dcf= DecimalFormat(“#,###”)
var dcfs= DecimalFormatSymbols(Locale.getDefault())
dcfs.groupingSeparator=’,’
dcf.decimalFormatSymbols=dcfs
println(dcf.format(x))
(a) 1000000
(b) 1,00,00,00
(c) 1,000,000
126
Commonly Important Libraries
3. What is the output to the screen when running the following commands?
var cal:Calendar=Calendar.getInstance()
cal.set(Calendar.DATE,9)
cal.set(Calendar.MONTH,3)
cal.set(Calendar.YEAR,2021)
var sdf= SimpleDateFormat(“dd/MM/yyyy”)
println(sdf.format(cal.time))
(a) 03/09/2021
(b) 04/09/2021
(c) 09/03/2021
(d) 09/04/2021
4. What is the output to the screen when running the following commands?
var x=Math.sqrt(Math.abs(-4).toDouble())
println(x)
(a) 2.0
(b) 2
(c) Compiler Error
(d) Runtime Error
5. How to random a number in [-100 … -50]? rd is a variable of Random
(a) -100-rd.nextInt(50)
(b) -100+rd.nextInt(50)
(c) -100+rd.nextInt(51)
(d) -100-rd.nextInt(51)
6. How to random a number in [-100 … 100]? rd is a variable of Random
(a) -100-rd.nextInt(201)
(b) -100-rd.nextInt(200)
(c) -100+rd.nextInt(200)
(d) -100+rd.nextInt(201)
7. What is the difference between using StringBuilder to concatenate strings
and using + operator to concatenate strings?
8. Write a program to enter x>0, n>0 and calculate the expression S(x, n)
S (x , n ) = x + x 2 + x 3 + … + x n
9. Write a program to enter x>0, n>0 and calculate the expression S(x, n)
127
Commonly Important Libraries
S (x , n ) = x 2 + x 4 + x 6 + … + x 2n
10. Write a program to enter x>0, n>0 and calculate the expression S(x, n)
x2 x3 xn
S (x , n ) = x + + +…+
2 3 n
11. Write a program to enter x>0, n>0 and calculate the expression S(x, n)
x2 x3 xn
S (x , n ) = x + + +…+
1+2 1+2+3 1 + 2 + 3 +…+ n
12. Write a program to enter n>=1 and calculate the expression S(n)
S (n ) = n + (n − 1) + (n − 2) + … + 2+ 1
128
Commonly Important Libraries
Table 2.
The results after inputting and displaying data after processing are similar
to the following table:
Table 3.
129
Commonly Important Libraries
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel & Isakova. (2020). Atomic Kotlin. Mindview LLC.
Dmitry & Svetlana. (2017). Kotlin in Action. Manning.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
130
131
Chapter 7
String Processing
ABSTRACT
In all programming languages, string processing is extremely important. This
chapter will present how to declare strings and summarize the commonly
used functions of strings, such as indexOf, lastIndexOf, contains, substring,
replace, trim, compare, plus, split, upper case and lowercase functions, etc.
Each function has sample code along with detailed explanations that make
it easy for readers to understand how to use basic string functions. In this
chapter, the book will present some of the most commonly used functions
in the string. At the end of the chapter there are exercises to help readers
improve the skills in string processing.
STRING PROCESSING
DOI: 10.4018/978-1-6684-6687-2.ch007
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
String Processing
functions in the string. At the end of the chapter there are exercises to help
readers improve the skills in string processing.
or
The Table 1 shows the properties and methods string in Kotlin (you can
see more at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/).
132
String Processing
IndexOf
IndexOf function returns the first position found, if not found returns -1. The
Listing 1 shows how to use this function.
Listing 1. LearnStringProcessing/App_IndexOf.kt
LastIndexOf
lastIndexOf function returns the last location found, if not found returns -1.
The Listing 2 shows how to use this function.
Listing 2. LearnStringProcessing/App_LastIndexOf.kt
133
String Processing
Contains
Contains function checks whether the contains exists in the original string
or not. The Listing 3 shows how to use this function.
Listing 3. LearnStringProcessing/App_Contains.kt
The results show that the output “Exist [Kotlin]”. The contains function
is used a lot to check the existence of the contains.
SubString
Listing 4. LearnStringProcessing/App_SubString.kt
1
2
fun main(args: Array<String>) {
3
val s = “Hello Kotlin Language”
4
println(“Original string:”)
5
println(s)
6
//get all the right string from startIndex=6
7
val s2 = s.substring(6)
8
println(“The string from startIndex=6:”)
9
//s2=Kotlin Language
10
println(s2)
11
//get child string from startIndex=6, endIndex=12(exclusive)
12
val s3 = s.substring(6, 12)
13
println(“The string from startIndex=6, endIndex=12(exclusive):”)
14
//s3=Kotlin
15
println(s3)
16
}
17
18
134
String Processing
Original string:
Hello Kotlin Language
The string from startIndex=6:
Kotlin Language
The string from startIndex=6, endIndex=12(exclusive):
Kotlin
In order to substring to the right of the string, use the substring with 1
parameter, in order to substring to the middle of the string, use the substring
with 2 parameters.
Replace
replace function converts old string to new string and we can use ignorecase.
The Listing 5 shows how to use this function.
Listing 5. LearnStringProcessing/App_Replace.kt
In the above example, in the replace function, the third argument is true,
which means the change is case-insensitive.
Results when running the program:
135
String Processing
ReplaceFirst
replaceFirst function converts old strings to new strings, but apply only to
the first string. The Listing 6 shows how to use this function.
Listing 6. LearnStringProcessing/App_ReplaceFirst.kt
1
fun main(args: Array<String>) {
2
var s = “Hello Kotlin Language, and Hello Python Language”
3
println(“The original string:”)
4
println(s)
5
//oldValue: “Hello”
6
//newVale: “Hi”
7
//true is ignorecase
8
s = s.replaceFirst(“Hello”, “Hi”,true)
9
println(“The string after replacing first:”)
10
println(s)
11
}
12
Although the original string has two “Hello” contains, the program only
applies to the first one.
Trim
136
String Processing
Listing 7. LearnStringProcessing/App_Trim.kt
1
fun main(args: Array<String>) {
2
var s:String= ” Tran Duy Thanh “
3
println(“The Original string:”)
4
println(“[$s]”)
5
println(“->The length of the string:${s.length}”)
6
println(“---------------------------------”)
7
//remove the whitespace string from start
8
var s2=s.trimStart()
9
println(“The string after calls the trimStart:”)
10
println(“[$s2]”)
11
println(“->The length of the string:${s2.length}”)
12
println(“---------------------------------”)
13
//remove the whitespace string from end
14
var s3=s.trimEnd()
15
println(“The string after calls the trimEnd:”)
16
println(“[$s3]”)
17
println(“->The length of the string:${s3.length}”)
18
println(“---------------------------------”)
19
//remove the whitespace string start and end
20
var s4=s.trim()
21
println(“The string after calls the trim:”)
22
println(“[$s4]”)
23
println(“->The length of the string:${s4.length}”)
24
}
25
137
String Processing
CompareTo
Listing 8. LearnStringProcessing/App_CompareTo.kt
s1=KOTLIN
s2=Kotlin
compareTo return 0 when ignoreCase true
compareTo return -32 when ignoreCase false
138
String Processing
Plus
plus(string x) appends the string x to the original string. The Listing 9 shows
how to use this function.
Listing 9. LearnStringProcessing/App_plus.kt
The plus function above pluses string, but it does not change the original
string that returns a new string, so we have to save this new address. You
can use the + sign (but do not use this sign too many times when you add
strings, especially when read from files or the internet). Also, you can use
StringBuilder to process string.
Split
The split(spilt string) function extracts the original string into List <String>.
The Listing 10 shows how to use this function.
139
String Processing
1
fun main(args: Array<String>) {
2
//the string with format: ID;FullName;Email
3
var s:String=”123;Tran Duy Thanh;[email protected]”
4
//split by ; character
5
//The elements are stored in the List
6
var arr:List<String> = s.split(“;”)
7
println(“Number of elements=”+arr.size)
8
//Get ID
9
var id=arr[0]
10
//Get Name
11
var fullName=arr[1]
12
//Get Email
13
var email=arr[2]
14
//print the informations:
15
println(“ID=$id”)
16
println(“Full Name=$fullName”)
17
println(“Email=$email”)
18
}
19
Number of elements=3
ID=123
Full Name=Tran Duy Thanh
[email protected]
140
String Processing
Now, the Book will do a string optimization program: For any string,
optimize the string as described: The string has no whitespace, the words
separated by a whitespace, the first characters of the words are UPPERCASE.
For example:
141
String Processing
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. Especially
understand how the libraries work to be able to apply well to actual projects.
Readers need to read many examples of how to handle strings from Kotlin,
since in this lesson the book has listed some of the most commonly used
methods, but there are countless other useful methods. Download source
code here: https://github.com/thanhtd32/kotlin/tree/main/LearnStringPro
cessing.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel &
Isakova, 2020; Bailey et al., 2021).
142
String Processing
Exercises
(a) Hello
(b) Kotlin
(c) Language
3. How to extract string “Language”?
(a) s.substring(13)
(b) s.substring(13,8)
(c) s.substring(14)
(d) s.substring(14,8)
4. What is the output to the screen when running the following commands?
143
String Processing
6. What is the output to the screen when running the following commands?
var s1=”D:/music/hello.mp3”
var s2=s1.substring(s1.lastIndexOf(“/”)+1)
println(s2)
(a) hello.mp3
(b) hello
(c) music
(d) mp3
7. What is the output to the screen when running the following commands?
var s1=”D:/music/hello.mp3”
var s2=s1.substring(
s1.indexOf(“/”)+1,
s1.lastIndexOf(“/”))
println(s2)
(a) hello.mp3
(b) hello
(c) music
(d) mp3
8. Write a program to check if a string is symmetric?
Eg, “radar” is a symmetric string, “hello” is not a symmetric string
9. Write a program to check if an email is valid or not?
10. What is the output to the screen when running the following commands?
var s:String=”Kotlin”
s=s.plus(“ Programming”)
s=s.plus(“ Language”)
println(s)
144
String Processing
11. What is the output to the screen when running the following commands?
var s:String=”Kotlin”
s.plus(“ Programming”)
s.plus(“ Language”)
println(s)
145
String Processing
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel & Isakova. (2020). Atomic Kotlin. Mindview LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Jemerov, D. & Isakova, S. (2017). Kotlin in Action. Manning.
146
147
Chapter 8
Array Processing
ABSTRACT
Array is one of the very important data in software processing, it will be used
to store data in the form of a list. Almost all programming languages support
array processing, and so does the Kotlin language. However, with Kotlin,
arrays are a very powerful data type, which overcome many disadvantages
compared to other programming languages such as C++, C#, Java, etc.
The book has briefly mentioned some of the array types that are built-in in
Kotlin, such as: CharArray, BooleanArray, ByteArray, ShortArray, IntArray,
LongArray, FloatArray, and DoubleArray. Depending on the purpose of use,
programmers can choose different types of arrays; to help readers easily
understand how to declare and use one-dimensional arrays in Kotlin, the
book will use IntArray to illustrate in the examples below. Other types of
arrays Readers can infer. At the end of the chapter, there are exercises to
help readers improve programming skills to handle arrays.
ARRAY PROCESSING
Array is one of the very important data in software processing, it will be used
to store data in the form of a list. Almost programming languages support
array processing, and so does the Kotlin language. However, with Kotlin,
arrays are a very powerful data type, which overcomes many disadvantages
compared to other programming languages such as C++, C#, Java, etc.
In chapter data type, the book has briefly mentioned some of the array
types that are built-in in Kotlin, such as: CharArray, BooleanArray, ByteArray,
DOI: 10.4018/978-1-6684-6687-2.ch008
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Array Processing
Syntax
But readers need to keep in mind that element retrieval is just a tiny function
in Kotlin’s array, since with the array in Kotlin there are many methods, it
is an object built with countless efficient methods: min, max, average, sum,
search, sort ...
We can initialize an array in Kotlin with values by syntax, eg:
148
Array Processing
The above example, we initialize an array in Kotlin with values 10, 20,
21, 40, 8
Using Functions
The list some common attributes and methods of Arrays are shown in the
Table 1 (of course there are many other methods, when you find them, you
study more):
M[0]=100
M[1]=20
…
M[9]=-5
149
Array Processing
var x:Int=M[2]
for (i in M.indices)
print(“${M[i]}\t”)
for (i in M)
print(“$i\t”)
Other functions in the array are also easy to implement. A detailed example
of creating an M array has 10 elements with random values is shown in the
Listing 1.
Results after running the program:
150
Array Processing
Listing 1. LearnOneDimensionalArray/App_Array.kt
151
Array Processing
Listing 1. Continued
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. Especially
understand how the libraries work to be able to apply well to actual projects.
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnOneDimens
ionalArray.
Syntax
152
Array Processing
Using Functions
153
Array Processing
We use two iterative browsing for loop (indices). External loop is browsing
by line; inner loop is browsing by column. Each time we browse, we have
M [i] [j] as the element in the i th row and the j th column. We update the
data for this element.
To output the data of the elements in the array to the screen we do the
following:
for(i in M.indices)
{
for(j in M[i].indices)
{
print(“${M[i][j]}\t”)
}
println()
}
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. You need to
check out many other methods in the 2-dimensional array to be able to apply
well to your actual project.
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnTwoDiment
ionalArray.
154
Array Processing
Listing 2. LearnTwoDimentionalArray/App_2DArray.kt
155
Array Processing
Exercises
var M= doubleArrayOf(1.5,2.0,3.8,4.5)
var x=M.count { i->i>3 }
println(x)
(a) 3
(b) 2
(c) 0
(d) 5
4. What is the result after executing the code below?
var M= intArrayOf(10,20,15,40,30)
var x=M.count { i->i%2==0 }
println(x)
(a) 4
(b) 2
(c) 5
(d) 1
5. What is the result after executing the code below?
var M= intArrayOf(10,20,15,40,30)
var x=M.count { i->i%2!=0 }
println(x)
(a) 4
(b) 2
156
Array Processing
(c) 5
(d) 1
6. What is the result after executing the code below?
var M= intArrayOf(10,20,15,40,30)
var x=M.filter { i->i>=20 }
println(x)
var M= intArrayOf(10,20,15,40,30)
var x=M.filter { i->i>=20 }.sorted()
println(x)
• Receive user input, such as the name of the book to be searched or the
name of the author, and keywords
• Saving book information as a dictionary
• Find the desired book in the dictionary where book information is
stored.
You have to think about how to present the information so that the user
can enter it easily:
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel & Isakova. (2020). Atomic Kotlin. Mindview LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Jemerov, D., & Isakova, S. (2017). Kotlin in Action. Manning.
158
159
Chapter 9
Collections
ABSTRACT
Similar to other programming languages, arrays and collections are
indispensable data types in the process of processing list data. In the previous
chapter presented about arrays, there are some benefits of arrays, but in some
cases, arrays do not meet requirements and are difficult to implement. Usually,
the data has no change in quantity, no deleting or changing the position of
data, then it is appropriate to use an array, but when it comes to cases where
the data changes continuously, or the number of elements is not known in
advance, or the position in the list can be shuffled, using arrays is no longer
optimal, so collections are more optimal. This chapter will present hierarchical
collections so that readers have an overview of collections, and then Mutable
and Immutable collection are presented. The chapter also provides code and
detailed explanation to help readers easily grasp the working mechanism,
as well as be able to implement the collection in practice. At the end of the
chapter, there are exercises to help readers improve collection processing
programming skills.
COLLECTIONS
DOI: 10.4018/978-1-6684-6687-2.ch009
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Collections
it is appropriate to use an array, but when it comes to cases where the data
changes continuously, or the number of elements is not known in advance,
or the position in the list can be shuffled, using arrays is no longer optimal,
so collections are more optimal. This chapter will present hierarchical
collections so that readers have an overview of collections, and then Mutable
and Immutable collection are presented. The chapter also provides code and
detailed explanation to help readers easily grasp the working mechanism,
as well as be able to implement the collection in practice. At the end of the
chapter, there are exercises to help readers improve collection processing
programming skills.
Hierarchical Collection
Mutable Collections is a set of classes used to store data lists and can be
resized
Immutable Collections is a set of classes used to store a list of data and
cannot be resized
160
Collections
Both of these collections are easy to create and use, they are just a little
bit different in in terms of programming purpose.
Within this lesson, the book only shows about MutableList and List, please
do extra research about other Collections however, with MutableList and
List, we think you can handle almost all instances of archiving, interacting,
displaying data in the software.
Mutable Collections
MutableList is a collection that can resize data: Can add, edit, delete ...
This collection in Kotlin do not have their own constructor constructs,
but through mutableListOf()
Syntax:
161
Collections
The above list object is initialized with 5 elements and we can change the
size, information of list.
Here are some common methods used with MutableList in the Table 1.
Please do some extra research to find out other amazing methods. The
Listing 1 shows how to use the MutableList.
162
Collections
40
print(“${list[i]}\t”)
41
println()
42
println(“SUM=”+list.sum())
43
println(“MAX=”+list.maxOrNull())
44
println(“MIN=”+list.minOrNull())
45
println(“AVERAGE=”+list.average())
46
//filter odd number
47
var oddNumbers=list.filter { x->x%2==1 }
48
println(“Elements in MutableList are odd numbers:”)
49
for(i in oddNumbers.indices)
50
print(“${oddNumbers[i]}\t”)
51
println()
52
//filter to get the prime list
53
var primes=list.filter {
54
x->
55
var count=0
56
for(i in 1..x)
57
{
58
if(x%i==0)
59
count++
60
}
61
count==2
62
}
63
println(“Elements in MutableList is prime:”)
64
for(i in primes.indices)
65
print(“${primes[i]}\t”)
66
println()
67
}
68
10 4 5 8 9 0 7
Elements in MutableList after changing:
10 4 113 8 9 0 7
Elements in MutableList after delete:
10 4 113 9 0 7
Elements in MutableList after sort ascending:
0 4 7 9 10 113
Elements in MutableList after sort descending:
113 10 9 7 4 0
SUM=143
MAX=113
MIN=0
AVERAGE=23.833333333333332
Elements in MutableList are odd numbers:
113 9 7
Elements in MutableList is prime:
113 7
163
Collections
Immutable Collections
The above list object is initialized with 4 elements and we cannot change
the size, information of list. When we use List in our mind, we want it to be
readOnly, only to display data.
Here are some common properties nad methods used with List in Table 2.
164
Collections
Listing 2. LearnCollection/App_List.kt
We notice that most of the List methods do not change the List internally,
but it returns a new List.
165
Collections
We can see that the collection in Kotlin is very flexible and powerful, we
can customize the processing. The filter function is a revolution in filtering
data.
This is the end of the lesson, please pay attention the examples
above and do extra research to have a better understanding of the
lesson. Especially understand how the Collection works to be able to
apply well to actual projects. The source code can be downloaded at
the link: https://github.com/thanhtd32/kotlin/tree/main/LearnCollectio
n.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel &
Isakova, 2020; Bailey et al., 2021).
Exercises
var list=mutableListOf(4,3,8,2,5)
println(list.filter { i->!(i%2!=0)})
(a) [4, 8, 2]
(b) [3, 5]
(c) Compiler error
166
Collections
(a) [5]
(b) [10, 6, 7, 5]
(c) Compiler error
7. What is the result after executing the code below?
(a) [5]
(b) [10, 6, 7, 5]
(c) Compiler error
8. What is the result after executing the code below?
(a) [2, 4, 9]
(b) [9, 2, 4]
(c) [9, 4, 2]
9. What is the result after executing the code below?
(a) [2, 4, 9]
(b) [9, 2, 4]
(c) [9, 4, 2]
167
Collections
The program uses an endless loop and collection to let the user choose from
5 options as shown below:
do
{
println(“Enter/Search for Books:”)
println(“1. Book input”)
println(“2. Search by book name”)
println(“3. Search by author name”)
println(“4. Search by publisher name”)
println(“5. End”)
println(“select(1,2,3,4,5):”)
var choice= readln()
println(choice)
//process choice
}while (true)
If you select No. 1, you can enter title, author name, publisher name, price,
and publication year as follows:
• title>>
• Author’s name>>
• Publisher>>
• price>>
• Publication year>>
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel & Isakova. (2020). Atomic Kotlin. Mindview LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Jemerov, D., & Isakova, S. (2017). Kotlin in Action. Manning.
168
169
Chapter 10
Object-Oriented
Programming in Kotlin
ABSTRACT
Object-oriented programming (OOP) is a programming technique that allows
programmers to abstract objects in reality and create those objects in code,
this programming technique is based on the concept of classes and objects.
Objects include properties and methods, properties are information, specific
characteristics of each object; Methods are operations that an object is
capable of performing. A class is a data type that includes many predefined
properties and methods. Each class acts as a unit of combined methods and
properties. Kotlin is like other programming languages that support object-
oriented programming. OOP is a general concept; programming language
is just one of the tools to implement that concept. This means that if readers
already understand OOP, then C #, Java, Kotlin, etc. will share this concept
for implementation. The chapter provides illustrative and detailed explanations
to help readers easily understand OOP. And at the end of the chapter, there
are exercises to help readers practice and improve OOP skills as well as
review the knowledge in previous chapters.
DOI: 10.4018/978-1-6684-6687-2.ch010
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Object-Oriented Programming in Kotlin
In this lesson, the book will go over some of the concepts related to OOP,
then we’ll get familiar with an example of OOP installation using Kotlin.
170
Object-Oriented Programming in Kotlin
• Numerator
• Denominator
• Brand
• Color
• Number of wheels
• Number of doors
• Run forward
• Run backward
• Stop
Objects with similar properties (attributes and methods) are grouped into
a class that distinguishes them from others and is easy to manage.
A class is a classification of objects or types of objects.
Example 3:
171
Object-Oriented Programming in Kotlin
Package
Abstraction
Case 1:
Figure 1. Abstraction
172
Object-Oriented Programming in Kotlin
Case 2:
From the similar objects: Abstraction into a class, it only provides the
necessary attributes and methods of the object in the program, the Figure 2
shows this case.
Figure 2. Abstraction
Encapsulation
173
Object-Oriented Programming in Kotlin
Figure 3. Encapsulation
Inheritance
174
Object-Oriented Programming in Kotlin
175
Object-Oriented Programming in Kotlin
Right-click on src and choose New and then select Kotlin Class/File menu
item:
176
Object-Oriented Programming in Kotlin
On the New Kotlin Class/File screen, select Kind as Class, name the class
Triangle and press Enter to create the Triangle class
The first result when creating a class in Kotlin:
Code for Triangle (please follow these steps, the book will explain the
components in the following lessons). The Triangle class details is shown
in the Listing 1.
Listing 1. LearnOOP/Triangle
1
2 class Triangle {
3 var slide1:Double=1.0
4 var slide2:Double=1.0
5 var slide3:Double=1.0
6 constructor() constructor(slide1:Double,slide2:Double,slide3:Double)
7 {
8 this.slide1=slide1
9 this.slide2=slide2
10 this.slide3=slide3
11 }
12 fun perimeter():Double
13 {
14 return slide1+slide2+slide3
15 }
16 fun area():Double
17 {
18 var p=perimeter()/2
19 return Math.sqrt(p*(p-slide1)*(p-slide2)*(p-slide3))
20 }
21 }
22
177
Object-Oriented Programming in Kotlin
Listing 2. LearnOOP/AppTest.kt
1
fun main(args: Array<String>) {
2
var t1=Triangle(4.0,5.0,6.0)
3
println(“Information about triangle 1:”)
4
println(“Perimeter=”+t1.perimeter())
5
println(“Area=”+t1.area())
6
var t2=Triangle()
7
t2.slide1=7.5
8
t2.slide2=10.3
9
t2.slide3=15.5
10
println(“Information about triangle 2:”)
11
println(“Perimeter=”+t2.perimeter())
12
println(“Area=”+t2.area())
13
}
14
178
Object-Oriented Programming in Kotlin
This is the end of the lesson, please pay attention the examples above and
do extra research to have a better understanding of the lesson. In the next
lessons, the Book will go into details about each of the classes in Kotlin
The source code can be downloaded at the link. https://github.com/
thanhtd32/kotlin/tree/main/LearnOOP.
• Class name
• Constructors
• Attributes
• Getter/setter
• Methods
class Student {
}
Unlike other languages, Kotlin allows only one class name to be declared
without any other elements, the declaration is as follows:
class Student
179
Object-Oriented Programming in Kotlin
Class name should be set according to the following rules: First letter of
the words must be Uppercase; name does not contain any white space.
Kotlin supports two types of constructors (special functions, which default
to initializing objects for memory allocation) which are primary constructor
and secondary constructors.
It is important to note that the primary constructor can not contain any
code. If you want to initialize the variables using the primary constructor,
you must use the init{}, the Listing 3 shows how to create the Student class
and the primary constructor.
Listing 3. LearnPrimaryConstructor/Student
180
Object-Oriented Programming in Kotlin
Listing 4. LearnPrimaryConstructor/TestStudent.kt
Listing 5. LearnSecondaryConstructor/Student
1
2 class Student {
3 constructor()
4 {
5 println(“This is secondary constructor without arguments”)
6 }
7 constructor(code:Int,name:String)
8 {
9 println(“This is secondary constructor with 2 arguments”)
10 println(“Code=$code ; Name =$name”)
11 }
12 }
13
181
Object-Oriented Programming in Kotlin
Listing 6. LearnSecondaryConstructor/TestStudent.kt
1
fun main(args: Array<String>) {
2
//call secondary constructor without arguments
3
var tom=Student()
4
//call secondary constructor with 2 arguments
5
var kitty=Student(100,”Kitty Solidate”)
6
}
7
Attributes are what belong to the object, e.g., 1 Student has the following
information: Student code, name, year of birth ... then these informations are
the attributes of Student object.
Kotlin, like other languages, provides a number of Visibility Modifiers
(private, protected, public, default) for the following properties:
182
Object-Oriented Programming in Kotlin
Listing 7. LearnAttribute/Student
1
2
class Student {
3
//Declare 2 attributes for Student with default modifier
4
var code:Int=0
5
var name:String=””
6
constructor()
7
{
8
println(“This is secondary constructor without arguments”)
9
}
10
constructor(code:Int,name:String)
11
{
12
println(“This is secondary constructor 2 arguments”)
13
this.code=code
14
this.name=name
15
}
16
}
17
18
As stated above, the two attributes code and name, which are default
modifiers, do not specify in the same package any object that can access these
attributes. The Listing 8 shows how to use the Student class and it’s attributes.
Listing 8. LearnAttribute/TestStudent.kt
1
fun main(args: Array<String>) {
2
//create lucy object with default constructor
3
var lucy=Student()
4
//access attributes and assign the value
5
lucy.code=500
6
lucy.name=”Lucy Brian”
7
println(“Information of Lucy:”)
8
println(“Code =${lucy.code}”)
9
println(“Name=${lucy.name}”)
10
println(“--------------------”)
11
//create crystal object with secondary constructor
12
var crystal=Student(600,”Crystal Brian”)
13
println(“Information of Crystal:”)
14
println(“Code =${crystal.code}”)
15
println(“Name=${crystal.name}”)
16
}
17
183
Object-Oriented Programming in Kotlin
Name=Lucy Brian
--------------------
This is secondary constructor 2 arguments
Information of Crystal:
Code =600
Name=Crystal Brian
The code for this example you can download at the link below: https://
github.com/thanhtd32/kotlin/tree/main/LearnAttribute.
For encapsulation, the attributes should declare private, when the declaration
property should be private. At this point the objects cannot be traced directly
to the given attributes, but through the getter / setter. The Listing 9 shows
private visibility modifier.
Listing 9. LearnAttribute/Student
1 class Student {
2 private var code:Int=0
3 private var name:String=””
4 }
1
fun main(args: Array<String>) {
2
var tom=Student()
3
tom.code=100
4
tom.name=”Tom”
5
}
6
If the properties in the class that for default and access in the same package
or attribute to the modifier are public, then we do not need to declare the
getter / setter.
Kotlin’s getter / setter declarations are different from Java, C #, and other
languages. Syntax for declaring getter / setter:
184
Object-Oriented Programming in Kotlin
getter is used to access the value of the attribute in the property, the setter
is used to change the value of the attribute in the property.
The Listing 11 shows how to create Properties for Attributes.
1 class Student {
2 //declare attributies
3 private var code:Int=0
4 private var name:String=””
5 //declare Code property for code attribute
6 public var Code:Int
7 get()
8 {
9 //retrieve the data of the attribute
10 return this.code
11 }
12 set(value)
13 {
14 //change attribute data
15 this.code=value
16 }
17 //declare Name property for name attribute
18 public var Name:String
19 get()
20 {
21 return this.name
22 }
23 set(value)
24 {
25 this.name=value
26 }
27 constructor()
28 {
29 }
30 constructor(code:Int,name:String)
31 {
32 this.code=code
33 this.name=name
34 }
35 }
In the coding above, we have two Getter / Setter Code and Name. External
objects will not be able to access the code and the name attributes that are only
accessed through the Getter / Setter Code and Name. The keyword get and set
above the IntelliJ IDEA software also suggests available for us, just type the
first letter is it hint and then press Enter itself appears. With set you notice
185
Object-Oriented Programming in Kotlin
that the value is the default parameter, which is the parameter that receives
the input value from the outside (i.e., changes the attribute information for the
object). The Listing 12 shows how to use the Student class and the Properties.
1
fun main(args: Array<String>) {
2
//Declare tom Student object
3
var tom=Student()
4
//call Code Property (set)
5
tom.Code=100
6
//call Name Property (get)
7
tom.Name=”Tom Hoping”
8
println(“The Information:”)
9
//call Code Property(get)
10
println(“Code = ${tom.Code}”)
11
//call Name Property(get)
12
println(“Name = ${tom.Name}”)
13
println(“-----------------”)
14
//We can use the constructor
15
var jerry=Student(200,”Jerry Cherry”)
16
//call Code Property(get)
17
println(“Code = ${jerry.Code}”)
18
//call Name Property(get)
19
println(“Name = ${jerry.Name}”)
20
}
21
The Information:
Code = 100
Name = Tom Hoping
-----------------
Code = 200
Name = Jerry Cherry
186
Object-Oriented Programming in Kotlin
In addition, we can use the following way to declare properties, the Listing
13 shows how to create the properties with another way.
1 class Student {
2 var Code:Int=0
3 get() = field
4 set(value) {field=value}
5 var Name:String=””
6 get() = field
7 set(value) {field=value}
8 }
In the example above, we do not declare the attribute code and name, but
always use the property Code and Name, the key field keyword represents
the property. The value variable passed to change the value of the attribute,
we can change another name, but we should keep the variable name as value.
We create the main function to test how to use the above Student class,
see the Listing 14.
Code = 900
Name = Daisy Newman
187
Object-Oriented Programming in Kotlin
The method is called behavior, the business process on the object. This is
the set of the strength of the object. Kotlin uses the fun keyword to declare
methods. These methods may have a return value or not.
The following Listing 15 shows the example how to add two methods
(returns a String value and returns no value at all).
1
class Student {
2
private var code:Int=0
3
private var name:String=””
4
public var Code:Int
5
get()
6
{
7
return this.code
8
}
9
set(value)
10
{
11
code=value
12
}
13
public var Name:String
14
get()
15
{
16
return name
17
}
18
set(value)
19
{
20
name=value
21
}
22
constructor()
23
{
24
}
25
constructor(code:Int,name:String)
26
{
27
this.code=code
28
this.name=name
29
}
30
fun printInfor()
31
{
32
println(“Details Of Information:”)
33
println(“Code= “+code)
34
println(“Name= “+name)
35
}
36
fun details():String
37
{
38
var s=”Details of Information:”
39
s=s.plus(“\nCode=”+code)
40
s=s.plus(“\n”)
41
s=s.plus(“Name=”+name)
42
return s
43
}
44
}
45
188
Object-Oriented Programming in Kotlin
In the Student class, printInfor() and details() methods are added. The
printInfor() method does not return a value, merely outputs the data of the
attributes. While the details() method returns a string type, the data of the
attributes will be appended to the string and return the result to details().
The following example demonstrates how to use the two functions in the
Listing 16.
1
fun main(args: Array<String>) {
2
var st=Student()
3
st.Code=300
4
st.Name=”Jonh Weird”
5
println(“Information by Property:”)
6
println(“Code:”+st.Code)
7
println(“Name:”+st.Name)
8
println(“-----Call the method printInfor()------”)
9
st.printInfor()
10
println(“-------Call the method detail()--------”)
11
var detail=st.details()
12
println(detail)
13
}
14
Information by Property:
Code:300
Name:Jonh Weird
--------Call the method printInfor()---------
Details Of Information:
Code= 300
Name= Jonh Weird
--------Call the method detail()---------
Details of Information:
Code=300
Name=Jonh Weird
189
Object-Oriented Programming in Kotlin
The toString() function is very special and useful, we often use this function
to output the internal data of the attribute when the object is output to the
screen, the Listring 17 shows how to create coding for toString() method.
190
Object-Oriented Programming in Kotlin
1
Class Student {
2
private var code:Int=0
3
private var name:String=””
4
public var Code:Int
5
get()
6
{
7
return this.code
8
}
9
set(value)
10
{
11
code=value
12
}
13
public var Name:String
14
get()
15
{
16
return name
17
}
18
set(value)
19
{
20
name=value
21
}
22
constructor()
23
{
24
}
25
constructor(code:Int,name:String)
26
{
27
this.code=code
28
this.name=name
29
}
30
fun printInfor()
31
{
32
println(“Details Of Information:”)
33
println(“Code= “+code)
34
println(“Name= “+name)
35
}
36
fun details():String
37
{
38
var s=”Details of Information:”
39
s=s.plus(“\nCode=”+code)
40
s=s.plus(“\n”)
41
s=s.plus(“Name=”+name)
42
return s
43
}
44
override fun toString(): String {
45
var s=”Details of Information:”
46
s=s.plus(“\nCode=”+code)
47
s=s.plus(“\n”)
48
s=s.plus(“Name=”+name)
49
return s
50
}
51
}
52
191
Object-Oriented Programming in Kotlin
In the main function, just print the object that automatically invokes
the toString() function, which is very beneficial. Objects contain a lot of
information and relationships, and toString () is just to help us export some
of the information we need to hide more information while still ensuring the
nature of the object, let’s see the Listing 19.
1
2 fun main(args: Array<String>) {
3 var st=Student()
4 st.Code=300
5 st.Name=”Jonh Weird”
6 println(“Information by Property:”)
7 println(“Code:”+st.Code)
8 println(“Name:”+st.Name)
9 println(“------Call the method printInfor()-----”)
10 st.printInfor()
11 println(“--------Call the method detail()-------”)
12 var detail=st.details()
13 println(detail)
14 println(“-----------Call toString()-------------”)
15 println(st)
16 }
17
Information by Property:
Code:300
Name:Jonh Weird
--------Call the method printInfor()---------
Details Of Information:
Code= 300
Name= Jonh Weird
--------Call the method detail()---------
Details of Information:
Code=300
Name=Jonh Weird
-----------Call toString()--------------
Details of Information:
Code=300
Name=Jonh Weird
The book has already presented the structure of a class in Kotlin, including
rules for creating:
192
Object-Oriented Programming in Kotlin
• Class name
• Constructors
• Attributes
• Getter/setter
• Methods
You pay attention to learn, practice again and try to understand it through
the examples above. In the next lessons, the book will continue introducing
OOP in Kotlin (method types, overloading method, reference this), please
pay proper attention.
The source code can be downloaded at the link: https://github.com/
thanhtd32/kotlin/tree/main/LearnDeclareMethod.
Types of Methods
In previous lesson, the book has presented the rules for creating classes,
constructors, properties, getter / setter, methods... In this lesson, the boook
will continue introducing the Method types, those are Service method and
Support method.
Let’s go back to the example of the Triangle class, see the Listing 20, in
this Listing, we add service methods area(), perimeter() and support method
halfPerimeter().
The coding above, you observe the halfPerimeter() method is support
method because it is private, this method will support other Service methods
such as area().
For outer class, we can only access methods that are Service Method,
we cannot access the Support Method, the Listing 21 shows how to use the
service methods.
Results when running the program:
193
Object-Oriented Programming in Kotlin
1
2 class Triangle {
3 public var Slide1:Double=1.0
4 get() {return field}
5 set(value) {field=value}
6 public var Slide2:Double=1.0
7 get() {return field}
8 set(value) {field=value}
9 public var Slide3:Double=1.0
10 get() {return field}
11 set(value) {field=value}
12 constructor()
13 constructor(slide1:Double,slide2:Double,slide3:Double)
14 {
15 Slide1=slide1
16 Slide2=slide2
17 Slide3=slide3
18 }
19 //This is service method
20 public fun perimeter():Double
21 {
22 return Slide1+Slide2+Slide3
23 }
24 //This is support method
25 private fun halfPerimeter(): Double {
26 return perimeter() / 2
27 }
28 //This is service method
29 public fun area():Double
30 {
31 var p=halfPerimeter()
32 return Math.sqrt(p*(p-Slide1)*(p-Slide2)*(p-Slide3))
33 }
34 }
35
1
fun main(args: Array<String>) {
2
var ta1= Triangle()
3
ta1.Slide1=4.0
4
ta1.Slide2=5.0
5
ta1.Slide3=6.0
6
var area=ta1.area()
7
var perimeter=ta1.perimeter()
8
//var ahalf=ta1.halfPerimeter()
9
//this command above will be errored
10
//because halfPerimeter() cannot access
11
println(“Area and Perimeter of the ta1:”)
12
println(“Area =$area”)
13
println(“Perimeter = $perimeter”)
14
println(“-------------”)
15
var ta2=Triangle(7.0,8.0,9.0)
16
println(“Area and Perimeter of the ta2:”)
17
println(“Area =${ta2.area()}”)
18
println(“Perimeter = ${ta2.perimeter()}”)
19
}
20
194
Object-Oriented Programming in Kotlin
Area =26.832815729997478
Perimeter = 24.0
This Reference
195
Object-Oriented Programming in Kotlin
196
Object-Oriented Programming in Kotlin
above, the book draws 2 variables from the line 4 and point to the variable
line 6, So obviously it generates an error (the first one is the wrong reference,
the second is the default variable in the arguments of the function, Kotlin
assumes that readOnly (val) cannot be changed.
So, in this case we must use the keyword this to indicate the program: This
is the current object in the class, we must access the Instance Variable. That
why we have to use the keyword this, so this reference will be as follows in
the Figure 12.
Overloading Method
197
Object-Oriented Programming in Kotlin
• Overloading is a feature of the same class that has many methods of the
same name, but different in terms of signature.
• Signature includes: The number of arguments or data types of
arguments or order of arguments.
• The return type is not included in the signature
• The benefit of overloading is the ability to reuse the method and help
to call the function “flexible”.
• Constructors are special instances of the Overloading Method
For example:
1 class Product {
2 public var Id:Int = 0
3 set(value) {field=value}
4 get() {return field}
5 public var Name:String = ““
6 set(value) {field=value}
7 get() {return field}
8 public var UnitPrice:Double=0.0
9 set(value) {field=value}
10 get() {return field}
11 constructor()
12 constructor(id:Int,name:String)
13 {
14 this.Id=id
15 this.Name=name
16 }
17 constructor(id:Int,name:String,unitPrice:Double)
18 {
19 this.Id=id
20 this.Name=name
21 this.UnitPrice=unitPrice
22 }
23 fun printInfor()
24 {
25 println(“Id = ${this.Id}”)
26 println(“Name = ${this.Name}”)
27 println(“UnitPrice = ${this.UnitPrice}”)
28 }
29 fun printInfor(id:Int,name:String,price:Double)
30 {
31 println(“Id = $id”)
32 println(“Name = $name”)
33 println(“UnitPrice = $price”)
34 }
35 }
198
Object-Oriented Programming in Kotlin
In the example above you see the constructor, The book has created 3
constructors with different number of arguments. And there are 2 printInfor
functions with different quantity of arguments (printInfor function on
command line 23 has no parameters, while printInfor on command line 29 has
3 parameters). Here are two examples: Overloading Method the methods
have the same name but different Signature, please see the Figure 13.
199
Object-Oriented Programming in Kotlin
200
Object-Oriented Programming in Kotlin
1
fun main(args: Array<String>) {
2
//Constructor 0 arguments is called
3
var p1=Product()
4
p1.Id=100
5
p1.Name=”Coca”
6
p1.UnitPrice=2.0
7
//Constructor 2 arguments is called
8
var p2=Product(200,”Pepsi”)
9
p2.UnitPrice=2.5
10
//Constructor 3 arguments is called
11
var p3=Product(300,”Sting”,3.0)
12
println(“Details of object p1:”)
13
p1.printInfor()
14
println(“Details of object p2:”)
15
p2.printInfor()
16
println(“Details of object p3:”)
17
p3.printInfor()
18
println(“Details of object p3:”)
19
p3.printInfor(p3.Id,p3.Name,p3.UnitPrice)
20
}
21
Of course, during the coding process we will use a lot of overloading for
its huge benefit, this lesson will help you know how to install the overloading
technique, you can apply thi into actual projects.
Kotlin also supports a special Overloading Method called vararg (also
known as Parameter list). This is a special case of Overloading Method (the
201
Object-Oriented Programming in Kotlin
1
fun countOfEvenNumber(vararg numbers: Int):Int {
2
var n=numbers.count { x->x%2==0 }
3
return n
4
}
5
fun main(args: Array<String>) {
6
var n1=countOfEvenNumber(1,2,3,4)
7
println(“Even numbers=$n1”)
8
var n2=countOfEvenNumber(2,4,3,8,6)
9
println(“Even numbers=$n2”)
10
var n3=countOfEvenNumber()
11
println(“Even numbers=$n3”)
12
var n4=countOfEvenNumber(1,2,3,4,5,6,7,8,9,20,18)
13
println(“Even numbers=$n4”)
14
}
15
Even numbers=2
Even numbers=4
Even numbers=0
Even numbers=6
Static Technique
202
Object-Oriented Programming in Kotlin
1 class A {
2 companion object
3 {
4 fun printData()
5 {
6 println(“The Print Data method”)
7 }
8 var data:Int=100
9 }
10 }
In class A, the data attribute and the printData() method are declared in the
companion block so they are static. When declared static, it will be accessed
directly from the class name:
[Class name].[Method()] is also known as class method
[Class Name].[Attribute] is also known as class member.
The Listing 27 shows how to call the static method.
The code above we do not create any object, but we use the class A itself
to directly access the methods and properties, run the statement, and see the
results:
Note that static attributes are used to share memory, it is under the
management of the class, not the object. So, if you write functions that change
the value of an attribute, then if any object changes the value of this static
attribute, all other objects will also see that change, the Listing 28 shows
creating method to access the static attribute.
203
Object-Oriented Programming in Kotlin
1 class A {
2 companion object
3 {
4 fun printData()
5 {
6 println(“The Print Data method”)
7 }
8 var data:Int=100
9 }
10 fun changeData(x:Int)
11 {
12 data=x
13 }
14 fun getData():Int
15 {
16 return data
17 }
18 }
1
2 fun main(args: Array<String>) {
3 //call static printData() method
4 A.printData()
5 //call static data attribute
6 println(A.data)
7 var a1=A()
8 a1.changeData(200)
9 println(“data be called by a1:”+a1.getData())
10 var a2=A()
11 println(“data be called by a2:”+a2.getData())
12 //a2 change data to 300
13 a2.changeData(300)
14 println(“data be called by a1:”+a1.getData())
15 }
16
204
Object-Oriented Programming in Kotlin
In previous lesson, the book has detailed the types of methods, this, overloading,
parameter list, and so on. This is one of the most important techniques in
object-oriented programming. In this lesson, the book will introduce about
Data Classes, Nested Classes, Inner Classes, Enum Classes in Kotlin.
Data Classes
During processing, we often just need to store data without methods. Kotlin
supports this function by helping us create a special class called Data Class.
The Data Class in Kotlin will automatically provide:
• equals() / hashCode()
• toString()
• componentN()
• copy()
The Listing 30 shows how to declare and use the Data Class.
205
Object-Oriented Programming in Kotlin
1
fun main(args: Array<String>) {
2
//Create a data class with name User
3
data class User(
4
var UserName:String,
5
var Password:String)
6
//create an User object
7
var user1=User(
8
UserName = “john”,
9
Password = “113@114Xa”)
10
println(“User information of user 1:”)
11
println(user1.toString())
12
println(“User Name =${user1.UserName}”)
13
println(“Password=${user1.Password}”)
14
//copy data:
15
var user2=user1.copy()
16
println(“User information of user 2:”)
17
println(user2.toString())
18
//copy data and change value for Property
19
var user3=user1.copy(Password =”12345678”)
20
println(“User information of user 3:”)
21
println(user3.toString())
22
}
23
In command from line 3 to line 5, we see a Data Class named User created,
it has two properties is UserName and Password
Command lines 7 to line 9 create a user1 object of type User. At the same
time, this object is initialized with values for the Property UserName and
Password.
Command line 10 to command line 13 outputs the data of the user1 object.
Command line 16 uses the copy() function to copy data in memory for
the user2 object (at this time a new memory cell appears and user2 manages
this memory cell, in this new memory cell the data is copied raw copy from
the memory cell in the user1 object).
Command line 20 is also used to copy data in the memory cell that user1 is
managing to the user3 object to manage, but the Password property is changed.
Results when running the program:
206
Object-Oriented Programming in Kotlin
Nested Classes
Kotlin, like other programming languages, has the ability to allow this class
to nest in other Nested classes. Note that Nested classes will not be able to
access member variables in the Outer class.
The Listing 31 shows how to create the Nested class.
1
class Outer {
2
var name: String = “Outer”
3
fun sayHelloOuter()
4
{
5
println(“Hello Outer”)
6
}
7
fun useNested()
8
{
9
var nt=Nested()
10
nt.doSomething()
11
}
12
class Nested {
13
//nested class can not access attribute or
14
// function in the outer class, such as:
15
// -name attribute,
16
// -sayHelloOuter() function
17
fun doSomething()
18
{
19
println(“The Nested class”)
20
}
21
}
22
}
23
207
Object-Oriented Programming in Kotlin
Inner Classes
Kotlin, like other programming languages, has the ability to allow this class
to nest in another Inner class. Note that Inner classes will be able to access
member variables in the Outer class, let’s see the Listing 33.
The code above shows the keyword inner in front of the Inner class. But the
constructor of inner class Inner can be called only with receiver of containing
class, we can not access the Inner outside of the outer class.
The Listing 34 shows the main function to use the inner class.
Running the program will result in output 1 to the screen.
208
Object-Oriented Programming in Kotlin
1 class Outer {
2 var name: String = “Outer”
3 fun sayHelloOuter()
4 {
5 println(“Hello Outer”)
6 }
7 fun useInner()
8 {
9 var inn=Inner()
10 inn.doSomething()
11 }
12 inner class Inner {
13 //inner class can access attribute or
14 // function in the outer class, such as:
15 // -name attribute,
16 // -sayHelloOuter() function
17 fun doSomething()
18 {
19 println(“The function in the Inner class”)
20 println(“The name from outer=$name”)
21 sayHelloOuter()
22 }
23 }
24 }
1
fun main(args: Array<String>) {
2
//cannot create an inner object:
3
//Constructor of inner class Inner can be called
4
//only with receiver of containing class
5
//var in=Outer.Inner()//can not
6
//create an outer object:
7
var ot=Outer()
8
//call method:
9
ot.useInner()
10
}
11
Enum Classes
Enum is also a kind of special class in Kotlin (like other C # languages, java ...)
The Figure 15 shows how to declare Enum in Kotlin is very simple, similar
to other programming languages.
When creating new file, we select Kind as Enum class, Name which is
the location to name Enum. For example, we define Grade and press enter,
and writing the enum class as the Listing 35.
You can use this Enum as the Listing 36 by create a Student class.
209
Object-Oriented Programming in Kotlin
1 class Student {
2 var Code:Int=0
3 var Name:String=””
4 var GPA:Double=0.0
5 constructor()
6 constructor(code:Int,name:String,gpa:Double)
7 {
8 Code=code
9 Name=name
10 GPA=gpa
11 }
12 public fun getGrade():Grade
13 {
14 if(GPA==4.0)return Grade.A
15 if(GPA==3.0)return Grade.B
16 if(GPA==2.0)return Grade.C
17 if(GPA==1.0)return Grade.D
18 if(GPA==0.0)return Grade.F
19 return Grade.UNKNOW
20 }
21 }
210
Object-Oriented Programming in Kotlin
The getGrade() function will rely on GPA to calculate the Grade for each
Student.
The Listing 37 shows how to call the Student class with Enum.
1
2
fun main(args: Array<String>) {
3
var st1=Student(100,”Mr John”,4.0)
4
println(“Code=${st1.Code}”)
5
println(“Name=${st1.Name}”)
6
println(“GPA=${st1.GPA}”)
7
println(“Grade=${st1.getGrade()}”)
8
println(“-----------------”)
9
var st2=Student()
10
st2.Code=200
11
st2.Name=”Mr Peter”
12
st2.GPA=2.0
13
println(“Code=${st2.Code}”)
14
println(“Name=${st2.Name}”)
15
println(“GPA=${st2.GPA}”)
16
println(“Grade=${st2.getGrade()}”)
17
}
18
21
Code=100
Name=Mr John
GPA=4.0
Grade=A
-----------------
Code=200
Name=Mr Peter
GPA=2.0
Grade=C
So far, the book has covered all the special classes in Kotlin (Data Classes,
Nested Classes, Inner Classes and Enum classes). Readers pay attention to
learn, practice again and try to understand it through the examples above.
In the next lessons, the book will continue to talk about object-oriented
programming in Kotlin (inheritance), readers pay attention to the track. The
sourcode can be downloaded at the link: https://github.com/thanhtd32/kotlin/
tree/main/LearnEnum.
211
Object-Oriented Programming in Kotlin
Class Inheritance
In this lesson, the book will present the knowledge related to the inheritance
in object-oriented programming. Before going into the installation procedure
of the Kotlin inheritance, The book briefs about the concept of inheritance.
What Is Inheritance?
Inheritance is the REUSE of existing code, we can extend the new code
from the existing code, to improve programming efficiency. We review the
concept at the beginning of the object orientation that the book mentioned:
Objects often share some of the same characteristics, behaviors which are
grouped together. Example of inheritance is shown in te Figure 16.
212
Object-Oriented Programming in Kotlin
Dog and Cat have some properties of animals, so they both inherit from
Animal class. Example of inheritance in Employee is shown in the Figure 17.
The book will write a project in Figure 18 as shown above. In Kotlin, to write
the inheritance class we take the following steps in the Listing 38. First, we
create the Employee Generalization Class (superclass).
213
Object-Oriented Programming in Kotlin
214
Object-Oriented Programming in Kotlin
We use a colon (:) to inherit, look at the picture above we know how to
write OfficialEmployee inherited from Employee (After writing the correct
inheritance syntax, we move the mouse to the OfficialEmployee class and
select Implement members as shown above.).
Above, Readers see it as red error, it is actually because Employee class
is abstract class. Subclasses inheriting from the abstract class are forced to
override the whole abstract class method of the superclass. IntelliJ IDEA
supports us with this override tool. Readers move mouse to where the error,
it will appear on the screen with the Implement members line as shown
above, select it and press Enter, the Implement Members screen will appear
as below in the Figure 20.
215
Object-Oriented Programming in Kotlin
Select abstract parent methods and click OK, it will automatically generate
Coding as follows in the Listing 39. (It is also called overriding method.)
1
class OfficialEmployee:Employee {
2
override fun calculateSalary(dayofWork: Int): Double
3
{
4
TODO(“Not yet implemented”)
5
}
6
}
7
1 class OfficialEmployee:Employee {
2 constructor():super()
3 constructor(code:Int,name:String):super(code,name)
4 {
5 }
6 override fun calculateSalary(dayofWork: Int): Double
7 {
8 if(dayofWork>=22)
9 return 5000.0
10 return 5000.0-100*(22-dayofWork)
11 }
12 }
1 class TemporaryEmployee:Employee {
2 constructor():super()
3 constructor(code:Int,name:String):super(code,name)
4 {
5 }
6 override fun calculateSalary(dayofWork: Int): Double
7 {
8 return 100.0*dayofWork
9 }
10 }
216
Object-Oriented Programming in Kotlin
Information of emp1:
100-Mr John
Salary of emp1=5000.0
------------------------
Information of emp2:
200-Mr Peter
Salary of emp2=300.0
Above, the book has mentioned Override, so what is it? Overriding Method
can be understood:
• In a set of blood related classes that have the same signature (different
method content)
• Overriding methods help programmers define different behaviors for
different objects, but they use the same method name.
• For example: Official employees and temporary employees have the
method of calculating salary, however the method of salary calculation
of these two objects will be different.
217
Object-Oriented Programming in Kotlin
1
interface MyInterface {
2
fun bar()
3
fun foo() {
4
// optional body
5
}
6
}
7
1
class Child: MyInterface {
2
override fun bar() {
3
// body
4
}
5
}
6
We note that, for Kotlin, inheriting from Classes is just for single inheritance
like Java, C #. Inheritance from the Interface allows multiple inheritance, so
it is sometimes conflicting if the interfaces that it inherits from have abstract
methods with identical names. In this case, Kotlin resolves as follows in the
Listing 45.
218
Object-Oriented Programming in Kotlin
1 interface A {
2 fun foo() { print(”A”) }
3 fun bar()
4 }
5 interface B {
6 fun foo() { print(”B”) }
7 fun bar() { print(”bar”) }
8 }
9 class C: A {
10 override fun bar() { print(”bar”) }
11 }
12 class D: A, B {
13 override fun foo() {
14 super<A>.foo()
15 super<B>.foo()
16 }
17 override fun bar() {
18 super<B>.bar()
19 }
20 }
Let’s see an example of calculating the perimeter and area of circles and
squares according to the inheritance model as in Figure 21.
219
Object-Oriented Programming in Kotlin
We create the IFormula interface with 2 functions, these are area() function
and perimeter() function. Let’s see the Listing 46.
1 interface IFormula {
2 fun area(): Double
3 fun perimeter(): Double
4 }
And then we create the Square class and implements from IFormula
interface. We proceed to override the methods to calculate the perimeter and
area, adjust the calculation formulas accordingly. The Listing 47 shows how
to create write the Square class.
1
class Square:IFormula {
2
var slide:Double = 0.0
3
constructor()
4
constructor(slide:Double)
5
{
6
this.slide=slide
7
}
8
override fun area(): Double {
9
return Math.pow(slide, 2.0);
10
}
11
override fun perimeter(): Double {
12
return 2*slide;
13
}
14
}
15
And then we create the Circle class and implements from IFormula
interface. We proceed to override the methods to calculate the perimeter and
area, adjust the calculation formulas accordingly. The Listing 48 shows how
to create write the Circle class.
220
Object-Oriented Programming in Kotlin
1
class Circle:IFormula {
2
var radius:Double=0.0
3
constructor()
4
constructor(radius:Double)
5
{
6
this.radius=radius
7
}
8
override fun area(): Double {
9
return Math.PI*Math.pow(radius, 2.0);
10
}
11
override fun perimeter(): Double {
12
return 2*Math.PI*radius
13
}
14
}
15
Finally, we create the main function to test the program in the Listing 49.
1
2 fun main(args: Array<String>) {
3 var c = Circle(5.0)
4 System.out.println(“Perimeter of the circle= “)
5 System.out.println(c.perimeter())
6 System.out.println(“Area of the circle= “)
7 System.out.println(c.area())
8 var s = Square(5.0)
9 System.out.println(“Perimeter of the square = “)
10 System.out.println(s.perimeter())
11 System.out.println(“Area of the square=”)
12 System.out.println(s.area())
13 }
14
221
Object-Oriented Programming in Kotlin
In this lesson, the book will introduce more about Alias and automatic garbage
collection mechanism in Kotlin.
Alias is the ability that in a memory cell there are multiple objects pointing
to (> = 2 objects)
The automatic garbage collection mechanism automatically recovers
memory when the memory is no longer managed by the object.
These two concepts are extremely important, and Readers need to make
sure understanding it to be able to handle memory management issues when
executing projects.
Now the book will go into details about the process of creating Alias and
garbage collection in Kotlin (it is similar in other languages).
Because Kotlin runs in the JVM platform, the mechanism works the same
way as Java.
1 class Fraction {
2 var Numerator:Int=1
3 get() {return field}
4 set(value) {field=value}
5 var Denominator:Int=1
6 get() {return field}
7 set(value) {field=value}
8 constructor(numerator: Int, denominator: Int) {
9 this.Numerator =numerator
10 this.Denominator = denominator
11 }
12 override fun toString(): String {
13 return “$Numerator/$Denominator”
14 }
15 }
222
Object-Oriented Programming in Kotlin
fractionA=fractionB
Then the above command: The language says “Fraction A Equals Fraction
B,” but the computer system will work under the “The fraction A points to
the memory area allocated by fraction B” In other words, “Memory area
B” now has two object variables pointing to (co-management). Figure 23
shows the alias.
223
Object-Oriented Programming in Kotlin
Thus, Alias appears in “memory area B”. At this time, there will be two
phenomena as follows:
224
Object-Oriented Programming in Kotlin
The following figure illustrates the GC (garbage collection) in the Figure 24.
In the main function we have the codes following in the Listing 51.
Command line 8 generates two phenomena: The first is the Alias (fractionA
and fractionB point to a memory cell), the second is the automatic garbage
collection mechanism automatically reclaim the memory allocated to the
fractionA in line 2 (because at this point the fractionA has pointer over the
memory of fractionB). When running the main function, what is the result?
Numerator of A=1
Denominator of A=5
225
Object-Oriented Programming in Kotlin
Numerator of B=3
Denominator of B=7
-----Alias------
Numerator of A=3
Denominator of A=7
Numerator of A=1
Denominator of A=5
Numerator of B=3
Denominator of B=7
-----Alias------
Numerator of A=3
Denominator of A=7
226
Object-Oriented Programming in Kotlin
Numerator of B=2
Denominator of B=9
1 class Fraction:Cloneable {
2 var Numerator:Int=1
3 get() {return field}
4 set(value) {field=value}
5 var Denominator:Int=1
6 get() {return field}
7 set(value) {field=value}
8 constructor(numerator: Int, denominator: Int) {
9 this.Numerator =numerator
10 this.Denominator = denominator
11 }
12 override fun toString(): String {
13 return “$Numerator/$Denominator”
14 }
15 fun copy():Fraction
16 {
17 var f:Fraction=clone() as Fraction
18 return f
19 }
20 }
227
Object-Oriented Programming in Kotlin
We see the Fraction class inheriting from Cloneable and the book has
added the copy() function to the fraction class itself. This function simply
calls Cloneable’s clone() command to create a new version of the object (the
same data is stored in different memory cells).
Numerator of A=1
Denominator of A=5
Numerator of B=3
Denominator of B=7
-----Alias------
Numerator of A=3
Denominator of A=7
Numerator of B=2
Denominator of B=9
Numerator of C=114
228
Object-Oriented Programming in Kotlin
Denominator of C=113
Numerator of A=2
Denominator of A=9
The book has presented the alias and Automatic Garbage Collection
Mechanism in Kotlin. Please pay attention to learn, practice again and try to
understand it through the examples above. In the next lessons, the book will
introduce the Extension method in Kotlin. The source code can be downloaded
at the link: https://github.com/thanhtd32/kotlin/tree/main/LearnCloneable.
Extensions Method
229
Object-Oriented Programming in Kotlin
Syntax:
fun [Data_Type].Function_name([ arguments]):[Return_Type]
{
this keyword in this object is in [Data_Type]
}
Example 1: Please add the Plus function to Int data type in the Listing 55.
1 fun Int.Plus(a:Int):Int
2 {
3 return this+a
4 }
5 fun main(args: Array<String>) {
6 var t=5.Plus(9)
7 println(“t=$t”)
8 var x1=9
9 var x2=10
10 var x3=x1.Plus(x2)
11 println(“x3=$x3”)
12 }
Readers look at the line 1, we write Int.Plus this is adding the Plus
function to Int Data type. Command line number 3 has the keyword this, this
here is the current object of type Int.
Readers continue to watch line number 6, see number 5.Plus (9). Because
5 is an integer type of Int that has just added the Plus function, so obviously 5
will have Method Plus. Readers notice that we do not know how Kotlin created
the Int, but we can still add the Plus method to the Int without knowing the
source code does not need to modify the existing source code.
When running the main function, we have the following result:
t=14
x3=19
230
Object-Oriented Programming in Kotlin
1 fun Int.CheckPrimeNumber():Boolean
2 {
3 var count=0
4 for(i in 1..this)
5 {
6 if(this%i==0)
7 count++
8 }
9 return count==2
10 }
1
fun Int.Plus(a:Int):Int
2
{
3
return this+a
4
}
5
fun Int.CheckPrimeNumber():Boolean
6
{
7
var count=0
8
for(i in 1..this)
9
{
10
if(this%i==0)
11
count++
12
}
13
return count==2
14
}
15
fun main(args: Array<String>) {
16
var t=5.Plus(9)
17
println(“t=$t”)
18
var x1=9
19
var x2=10
20
var x3=x1.Plus(x2)
21
println(“x3=$x3”)
22
var a=7
23
if(a.CheckPrimeNumber()==true)
24
{
25
println(“$a is prime”)
26
}
27
else
28
{
29
println(“$a is not prime”)
30
}
31
var b=9
32
if(b.CheckPrimeNumber()==true)
33
{
34
println(“$b is prime”)
35
}
36
else
37
{
38
println(“$b is not prime”)
39
}
40
}
41
231
Object-Oriented Programming in Kotlin
t=14
x3=19
7 is prime
9 is not prime
Example 3: Setting the Age Function for a Written Student’s Class, this class
is structured as follows in the Listing 58.
1
2
import java.util.*
3
class Student {
4
private var code:Int=0
5
private var name:String?=null
6
private var birthday: Date?=null
7
public var Code:Int
8
get() {return code}
9
set(value) {code=value}
10
public var Name:String?
11
get()= name
12
set(value) {name=value}
13
public var Birthday:Date?
14
get() = birthday
15
set(value) {birthday=value}
16
constructor(code: Int, name: String?, birthday: Date?) {
17
this.code = code
18
this.name = name
19
this.birthday = birthday
20
}
21
}
22
23
So how to set the age function for this Student class? (Do not change the
existing source code). We do the code as following in the Listing 59.
232
Object-Oriented Programming in Kotlin
1
2 import java.util.*
3 fun Student.Age():Int
4 {
5 var cal=Calendar.getInstance()
6 var currentYear=cal.get(Calendar.YEAR)
7 cal.time=this.Birthday
8 var yearBoy=cal.get(Calendar.YEAR)
9 return currentYear-yearBoy+1
10 }
11 fun main(args: Array<String>) {
12 var yob=Calendar.getInstance()
13 yob.set(Calendar.YEAR,1998)
14 yob.set(Calendar.MONTH,2)
15 yob.set(Calendar.DAY_OF_MONTH,15)
16 var st=Student(100,”Mr Peter”,yob.time)
17 var age=st.Age()
18 println(“Code of Student=${st.Code}”)
19 println(“Name of Student=${st.Name}”)
20 println(“Birthday of Student=${st.Birthday}”)
21 println(“Age of Student=${st.Age()}”)
22 }
23
Above, we add the Age () function into the Student class. Based on the
three examples above, Readers can apply to any projects.
When running the main function, what is the result?
Code of Student=100
Name of Student=Mr Peter
Birthday of Student=Sun Mar 15 15:34:13 KST 1998
Age of Student=24
The book has already presented the Extensions Method in Kotlin. Please
pay attention to learn, practice again and try to understand it through the
examples above. In the next lessons, the book will discuss the File Handling
in Kotlin very important during data storage processing. The source code
can be downloaded at the link: https://github.com/thanhtd32/kotlin/tree/main/
LearnExtensionMethod.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel
& Isakova, 2020; Bailey et al., 2021). Additionally, Java Object Oriented
Programming book is referenced in Schild (2019).
233
Object-Oriented Programming in Kotlin
Exercises
234
Object-Oriented Programming in Kotlin
Code
class A {
var x:Int=0
var y:Int=5
constructor(){ fun main(args: Array<String>) {
x=2 var a=A()
y=2 var b=a
} b.y=8
constructor(x:Int,y:Int){ println(“x=${a.x}, y=${a.y}”)
this.x=x }
this.y=y
}
}
Code
class A {
var x:Int=0
var y:Int=5
constructor(){
var a=A(3,5)
x=2
var b=a
y=2
b.y=4
}
println(“a(${a.x},${a.y})”)
constructor(x:Int,y:Int){
println(“b(${b.x},${a.y})”)
this.x=x
this.y=y
}
}
235
Object-Oriented Programming in Kotlin
Code
Code
class E {
fun main(args: Array<String>) {
companion object{
var e1=E()
var x:Int=10
e1.print()
}
var e2=E()
constructor(){x+=5}
E.x=8
fun print(){
e1.print()
println(x)
e2.print()
}
}
}
236
Object-Oriented Programming in Kotlin
27. After the process() function executes what value is printed to the screen?
class Outer {
var x:Int=10
class Data {
fun process(){
println(x)
}
}
}
(a) 10
(b) Error because inner class cannot access x
(c) Error because nested class cannot access x
28. After the process() function executes what value is printed to the screen?
class Outer {
private var x:Int=10
inner class Data {
fun process(){
println(x)
}
}
}
(a) 10
(b) Error because inner class cannot access x
(c) Error because cannot access private x
29. What is the result after executing the code below?
237
Object-Oriented Programming in Kotlin
Code
class Z:X,Y {
interface X { override fun func1() {
fun func1() println(“a”)
} }
interface Y { override fun func2() {
fun func2() println(“b”)
} }
fun main(args: Array<String>){ fun func3(){
var x1:X func1()
x1=Z() func2()
x1.func3()} }
}
Figure 26.
238
Object-Oriented Programming in Kotlin
239
Object-Oriented Programming in Kotlin
REFERENCES
Bailey, A., Greenhalgh, D., & Skeen, J. (2021). Kotlin Programming: The
Big Nerd Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel, B., & Isakova, S. (2020). Atomic Kotlin. Mindview, LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Jemerov & Isakova. (2017). Kotlin in Action. Manning.
Schild, H. (2019). Java the complete Reference (11th ed.). McGraw-Hill
Education.
240
241
Chapter 11
File Processing
ABSTRACT
During software deployment, different kinds of file will be used depending on
the specific case. The book will show the series of four file types: Text File,
Serialize File, XML File, JSon File so that readers have more options in file
processing. Why does program have to store data? As computer architecture
is mentioned, a program wants to work, every resource must be loaded into
memory, namely the RAM (Random Access Memory). The principle of RAM
is the clipboard, when the software is turned off the data in the memory
will no longer there. Assuming customers are entering 100 products, and
the power is suddenly cut, if there is no mechanism to save data from RAM
memory to the hard drive, customers will be losing all the data. Kotlin uses
JVM libraries to interact with the file, so programmers can invoke these
libraries. This chapter provides examples of handling saving and reading
files with different cases, which help readers to cover most of the processing
cases in practice. At the end of the chapter, there are exercises to improve
readers skills with file processing.
FILE PROCESSING
DOI: 10.4018/978-1-6684-6687-2.ch011
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
File Processing
be loaded into memory, namely the RAM (Random Access Memory). The
principle of RAM is the clipboard, when the software is turned off the data
in the memory will no longer there. Assuming customers are entering 100
products, and the power is suddenly cut, if there is no mechanism to save
data from RAM memory to the hard drive, customers will be losing all the
data. Kotlin uses JVM libraries to interact with the file, so programmers can
invoke these libraries. This chapter provides examples of handling saving
and reading files with different cases, which help readers to cover most of
the processing cases in practice. At the end of the chapter, there are exercises
to improve readers skills with file processing.
Text File is a way to store raw data, Readers can open the file to view the
structure, content and edit.
To save text files, similar to Java, Kotlin will have to import the following
libraries:
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.io.BufferedWriter
242
File Processing
Method Description
Creates a file output stream to write to the file with the
FileOutputStream(String name)
specified name.
Closes this file output stream and releases any system resources
void close()
associated.
FileDescriptor getFD() Returns the file descriptor associated.
void write(byte[] b) Writes b bytes from the specified byte array.
Writes len bytes from the specified byte array starting at offset
void write(byte[] b, int off, int len)
off.
void write(int b) Writes the specified byte.
Method Description
OutputStreamWriter(OutputStream out, String Creates an OutputStreamWriter that uses the named
charsetName) charset.
void close() Closes the stream, flushing it first.
void write(char[] cbuf, int off, int len) Writes a portion of an array of characters.
void write(int c) Writes a single character.
void write(String str) Writes a string.
243
File Processing
Method Description
Creates a buffered character-output stream that uses a
BufferedWriter(Writer out)
default-sized output buffer.
void close() Closes the stream, flushing it first.
void newLine() Writes a line separator.
void write(char[] cbuf, int off, int len) Writes a portion of an array of characters.
void write(int c) Writes a single character.
void write(String s, int off, int len) Writes a portion of a String.
var bw = BufferedWriter(osw)
Note that when accessing the file, we must put it in a try…catch block or
throw try catch. The Listing 1 is a complete illustration of the script to save
the text file.
244
File Processing
Listing 1. LearnTextFile/TestWriteTextFile.kt
1
import java.io.BufferedWriter
2
import java.io.FileOutputStream
3
import java.io.OutputStreamWriter
4
fun main(args: Array<String>) {
5
try {
6
var path=”d:/data.txt”
7
var fos = FileOutputStream(path)
8
var osw = OutputStreamWriter(fos, “UTF-8”)
9
var bw = BufferedWriter(osw)
10
bw.write(“Kotlin”)
11
bw.newLine()
12
bw.write(“Programming”)
13
bw.newLine()
14
bw.write(“Language”)
15
bw.close()
16
osw.close()
17
fos.close()
18
}
19
catch (ex:Exception)
20
{
21
ex.printStackTrace()
22
}
23
}
24
245
File Processing
To read text files, similar to Java, Kotlin will have to import the following
libraries:
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.BufferedReader
The class FileInputStream obtains input bytes from a file in a file system.
What files are available depends on the host environment. FileInputStream is
meant for reading streams of raw bytes such as image data. For reading streams
of characters, consider using FileReader. The Table 4 shows Constructor and
Method summary for FileInputStream.
Method Description
FileInputStream(String name) Creates a FileInputStream by path name.
Closes this file input stream and releases any system resources
void close()
associated.
Returns the FileDescriptor object that represents the
FileDescriptor getFD()
connection to the actual file.
int read() Reads a byte of data from this input stream.
Reads up to b bytes of data from this input stream into an
int read(byte[] b)
array of bytes.
Reads up to len bytes of data from this input stream into an
int read(byte[] b, int off, int len)
array of bytes.
var path=”d:/data.txt”
var fis = FileInputStream(path)
246
File Processing
Method Description
InputStreamReader(InputStream in, String
Creates an InputStreamReader that uses the named charset.
charsetName)
Closes the stream and releases any system resources
void close()
associated with it.
int read() Reads a single character.
int read(char[] cbuf, int offset, int length) Reads characters into a portion of an array.
Method Description
Creates a buffering character-input stream that uses a default-
BufferedReader(Reader in)
sized input buffer.
Closes the stream and releases any system resources
void close()
associated with it.
int read() Reads a single character.
int read(char[] cbuf, int off, int len) Reads characters into a portion of an array.
String readLine() Reads a line of text.
var br = BufferedReader(isr)
Note that when accessing the file, we must put it in a try…catch block or
throw try catch. The Listing 2 is a complete illustration of the script to read
the text file.
247
File Processing
Listing 2. LearnTextFile/TestReadTextFile.kt
1
import java.io.FileInputStream
2
import java.io.InputStreamReader
3
import java.io.BufferedReader
4
fun main(args: Array<String>) {
5
try {
6
var path=”d:/data.txt”
7
var fis = FileInputStream(path)
8
var isr = InputStreamReader(fis, “UTF-8”)
9
var br = BufferedReader(isr)
10
var line = br.readLine()
11
while (line != null) {
12
println(line)
13
line = br.readLine()
14
}
15
br.close()
16
isr.close()
17
fis.close()
18
}
19
catch (ex:Exception)
20
{
21
ex.printStackTrace()
22
}
23
}
24
Running the program, we have the results of reading data from d:/data.txt:
Kotlin
Programming
Language
Now we make a project to save the file and read the file on the object,
specifically we do it on the Product class (it has Code, Name, UnitPrice
properties), the project structure will be as follows in the Figure 2.
248
File Processing
The package tdt.com.model will store the Product class with the following
structure in the Listing 3.
249
File Processing
Listing 3. LearnTextFileObject/tdt.com.model/Product
1
2 package tdt.com.model
3 class Product {
4 public var Code:Int=0
5 get() {return field}
6 set(value) {field=value}
7 public var Name:String=””
8 get() {return field}
9 set(value) {field=value}
10 public var UnitPrice:Double=0.0
11 get() {return field}
12 set(value) {field=value}
13 constructor()
14 constructor(code: Int, name: String,
15 unitPrice: Double) {
16 this.Code = code
17 this.Name = name
18 this.UnitPrice = unitPrice
19 }
20 override fun toString(): String {
21 return “$Code\t$Name\t$UnitPrice”
22 }
23 }
24
Now we will write the class to save the Product list as follows (TextFileFactory
class), it is shown in the Listing 4.
250
File Processing
1 package tdt.com.io
2 import tdt.com.model.Product
3 import java.io.*
4 class TextFileFactory {
5 /**
6 * @author TranDuy Thanh
7 * @param data: Data is product list to be saved
8 * @param path: Storage path
9 * @return true if saved successfully, false if
10 saved fails
11 */
12 fun SaveFile(data:MutableList<Product>,
13 path:String):Boolean
14 {
15 try {
16 var fos = FileOutputStream(path)
17 var osw = OutputStreamWriter(fos, “UTF-8”)
18 var bw = BufferedWriter(osw)
19 //convert product to string format:
20 //”$Code\t$Name\t$UnitPrice”
21 //and save to file line by line
22 for (product in data) {
23 bw.write(product.toString());
24 bw.newLine();
25 }
26 bw.close();
27 osw.close();
28 fos.close();
29 return true
30 }
31 catch (ex:Exception)
32 {
33 ex.printStackTrace()
34 }
35 return false
36 }
37 /**
38 * @author TranDuy Thanh
39 * @param path:storage path to read data
251
File Processing
40
41
42 * @return Product list MutableList
43 */
44 fun ReadFile(path:String):MutableList<Product>
45 {
46 var data:MutableList<Product>
47 = mutableListOf()
48 try {
49 var fis = FileInputStream(path)
50 var isr = InputStreamReader(fis, “UTF-8”)
51 var br = BufferedReader(isr)
52 var line = br.readLine()
53 while (line != null) {
54 //string format:
55 “$Code\t$Name\t$UnitPrice”
56 //we split this string format
57 var arr = line.split(“\t”)
58 if (arr.size == 3) {
59 //remodel the Product object
60 var product: Product = Product()
61 product.Code = arr[0].toInt()
62 product.Name = arr[1]
63 product.UnitPrice =
64 arr[2].toDouble()
65 data.add(product)
66 }
67 line = br.readLine()
68 }
69 br.close()
70 isr.close()
71 fis.close()
72 }
73 catch (ex:Exception) {
74 ex.printStackTrace()
75 }
76 return data
77 }
78 }
79
80
Now create the main function in the file TestProduct.kt to test and save the
Product List as a Text File. The saveProduct() function is used to demonstrate
how to save a list of Products to a text file. The readProduct() function is
used to demonstrate how to read a list of Products from a text file and re-
model the object.
The main function provides options for the user to save the file, read the
file, or exit the program. It is shown in the Listing 5.
252
File Processing
Listing 5. LearnTextFileObject/tdt.com.test/TestProduct.kt
1
2 package tdt.com.test
3 import tdt.com.io.TextFileFactory
4 import tdt.com.model.Product
5 var path=”d:/Productdata.txt”
6 fun saveProduct()
7 {
8 var data:MutableList<Product> = mutableListOf()
9 var p1=Product(1,”Coca”,15.5)
10 data.add(p1)
11 var p2=Product(2,”Sting”,25.0)
12 data.add(p2)
13 var p3=Product(3,”Redbull”,17.0)
14 data.add(p3)
15 var tff= TextFileFactory()
16 var ret=tff.SaveFile(data,path)
17 if(ret)
18 {
19 println(“Save text file successfully”)
20 }
21 else
22 {
23 println(“Save text file failed”)
24 }
25 }
26 fun readProduct()
27 {
28 var tff= TextFileFactory()
29 var data:MutableList<Product> = tff.ReadFile(path)
30 for (product in data)
31 println(product)
32 }
33 fun main(args: Array<String>) {
34 while(true)
35 {
36 println(“1.Save Product into File”)
37 println(“2.Open Product from File”)
38 println(“3.Exit”)
39 println(“Your choice:”)
40 var s:String?= readLine()
41 if(s!=null)
42 {
43 if(s.equals(“1”))
44 saveProduct()
45 else if(s.equals(“2”))
46 readProduct()
47 else
48 break
49 }
50 }
51 }
52
253
File Processing
3.Exit
Your choice:
1
254
File Processing
So, we have saved and read Text File successfully, Readers apply yourself
to specific projects, save the structure of the Text File is by your decision,
in the above examples, the book saves each object is a line, and attributes
separated by a tab.
In the next lessons, the book will discuss the Serialize File Processing in
Kotlin is very important in the process of data storage.
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnTextFileO
bject.
The book has introduced Text File. In this lesson, the book will continue the
tutorial series on file handling, which is Serialize File in Kotlin.
Like Text File, Kotlin also uses JVM libraries to process Serialize, so it
is very similar to Java.
Serialize File allows us to “snap” the object onto the hard drive and restore
the image from the hard drive to memory. To save the form of Serialize, the
class stored on the hard drive must implement the Serializable interface.
Serializable Class
We see the structure of the Contact class as follows in the Listing 6. And we
want to serialize the Contact object to the hard drive.
255
File Processing
Listing 6. LearnSerializableFile/Contact
1
import java.io.Serializable
2
class Contact:Serializable {
3
public var Id:Int = 0
4
get() {return field}
5
set(value) {field=value}
6
public var Name:String=””
7
get() {return field}
8
set(value) {field=value}
9
public var Email:String=””
10
get() {return field}
11
set(value) {field=value}
12
constructor()
13
constructor(Id: Int,
14
Name: String,
15
Email: String) {
16
this.Id = Id
17
this.Name = Name
18
this.Email = Email
19
}
20
override fun toString(): String {
21
return “$Id\t$Name\t$Email”
22
}
23
}
24
To Serialize the Contact object to the hard drive, this class must implement
the Serializable interface.
In the main function we create and use Contact class as in the Listing 7. But
in this Listing we just create the contact object and print out the information.
Listing 7. LearnSerializableFile/TestSaveObject.kt
256
File Processing
The question is how to serialize this Contact object to file by serializing its
object to file? The library packages used to serialize the object into the file:
import java.io.FileOutputStream
import java.io.ObjectOutputStream
Method Description
ObjectOutputStream Creates an ObjectOutputStream that writes to the specified
(OutputStream out) OutputStream.
void write(int val) Writes a byte.
void writeByte(int val) Writes an 8 bit byte.
void writeInt(int val) Writes a 32 bit int.
void writeLong(long val) Writes a 64 bit long.
void writeFloat(float val) Writes a 32 bit float.
void writeDouble(double val) Writes a 64 bit double.
void writeUTF(String str) Primitive data write of this String in modified UTF-8 format.
void writeObject(Object obj) Write the specified object to the ObjectOutputStream.
void close() Closes the output stream.
var path=”d:/contact.data”
var fos= FileOutputStream(path)
var oos= ObjectOutputStream(fos)
oos.writeObject(c)
257
File Processing
oos.close()
fos.close()
The above code uses the FileOutputStream object and then passes it to the
ObjectOutputStream object to use, to save the object we call the writeObject
command. We need to call close() commands to close the file to finish saving
the file. The Listing 8, we edit the code to illustrates serializing the Contact
object to a file.
Listing 8. LearnSerializableFile/TestSaveObject.kt
1
2 import java.io.FileOutputStream
3 import java.io.ObjectOutputStream
4 fun main(args: Array<String>) {
5 var c=Contact()
6 c.Id=100
7 c.Name=”Dr. John”
8 c.Email=”[email protected]”
9 println(c)
10 var path=”d:/contact.data”
11 try {
12 var fos= FileOutputStream(path)
13 var oos= ObjectOutputStream(fos)
14 oos.writeObject(c)
15 oos.close()
16 fos.close()
17 println(“Save file successful!”);
18 }
19 catch (ex:Exception)
20 {
21 ex.printStackTrace()
22 }
23 }
24
258
File Processing
Method Description
ObjectInputStream Creates an ObjectInputStream that reads from the specified
(InputStream in) InputStream.
int read() Reads a byte of data.
byte readByte() Reads an 8 bit byte.
int readInt() Reads a 32 bit int.
long readLong() Reads a 64 bit long.
float readFloat() Reads a 32 bit float.
double readDouble() Reads a 64 bit double.
String readUTF() Reads a String in modified UTF-8 format.
Object readObject() Read an object from the ObjectInputStream.
void close() Closes the input stream.
259
File Processing
Listing 9. LearnSerializableFile/TestOpenObject.kt
1
import java.io.FileInputStream
2
import java.io.ObjectInputStream
3
fun main(args: Array<String>) {
4
var path=”d:/contact.data”
5
try
6
{
7
var fis= FileInputStream(path)
8
var ois= ObjectInputStream(fis)
9
var obj=ois.readObject()
10
var data= obj as Contact
11
ois.close()
12
fis.close()
13
println(data)
14
}
15
catch (ex:Exception)
16
{
17
ex.printStackTrace()
18
}
19
}
20
Here is the source code of the program, which can be downloaded at the
following link: https://github.com/thanhtd32/kotlin/tree/main/LearnSerializa
bleFile.
We upgrade the previous project by creating packages and classes to use for
storing a list of Contact objects. It is shown in the Figure 5.
260
File Processing
The structure of the Contact class is described as follows in the Listing 10.
261
File Processing
1
2 package tdt.com.model
3 import java.io.Serializable
4 class Contact:Serializable {
5 public var Id:Int = 0
6 get() {return field}
7 set(value) {field=value}
8 public var Name:String?=null
9 get() {return field}
10 set(value) {field=value}
11 public var Email:String?=null
12 get() {return field}
13 set(value) {field=value}
14 constructor()
15 constructor(Id: Int,
16 Name: String?,
17 Email: String?) {
18 this.Id = Id
19 this.Name = Name
20 this.Email = Email
21 }
22 override fun toString(): String {
23 return “$Id\t$Name\t$Email”
24 }
25 }
26
Name and Email are declared with String? so that they can contain null
values.
We create the SerializableFileFactory class provides two functions save
File and open File in detail as below in the Listing 11.
262
File Processing
1
2 package tdt.com.io
3 import java.io.FileInputStream
4 import java.io.FileOutputStream
5 import java.io.ObjectInputStream
6 import java.io.ObjectOutputStream
7 class SerializableFileFactory {
8 /**
9 * this function uses to save the object data
10 * into the file on the disk
11 * @param data the object to save
12 * @param path the path to save the data
13 * @return true/false
14 */
15 public fun saveFile(data:Any,path:String):Boolean
16 {
17 try {
18 var fos= FileOutputStream(path)
19 var oos= ObjectOutputStream(fos)
20 oos.writeObject(data)
21 oos.close()
22 fos.close()
23 return true
24 }
25 catch (ex:Exception)
26 {
27 ex.printStackTrace()
28 }
29 return false
30 }
31 /**
32 * this function use to deserialize the Object
33 * @param path the path of the file
34 * @return object or null
35 */
36 public fun openFile(path:String): Any?
37 {
38 try
39 {
40 var fis= FileInputStream(path)
41 var ois= ObjectInputStream(fis)
42 var data=ois.readObject()
43 ois.close()
44 fis.close()
45 return data
46 }
47 catch (ex:Exception)
48 {
49 ex.printStackTrace()
50 }
51 return null
52 }
53 }
54
263
File Processing
1 package tdt.com.test
2 import tdt.com.io.SerializableFileFactory
3 import tdt.com.model.Contact
4 /**
5 * This function is used to add a new Contact
6 * data entered by the user
7 */
8 fun addNewContact():Contact
9 {
10 print(“Id:”)
11 var id= readLine()!!.toInt()
12 print(“Name:”)
13 var name= readLine()
14 print(“Email:”)
15 var email= readLine()
16 var c=Contact(id,name,email)
17 return c
18 }
19 /**
20 * This function is used to export the list of
21 * contacts to the screen
22 */
23 fun printContacts(contacts:MutableList<Contact>)
24 {
25 for (c in contacts)
26 {
27 println(c)
28 }
29 }
30 fun main(args: Array<String>) {
31 var contacts= mutableListOf<Contact>()
32 while(true)
33 {
34 println(“1.Add new Contact”)
35 println(“2.Print Contacts”)
36 println(“3.Serialize Contacts”)
37 println(“4.Deserialize Contacts”)
38 println(“5.Exit”)
39 print(“Your choice:”)
264
File Processing
40
41
var s:String?= readLine()
42
if(s!=null)
43
{
44
if(s.equals(“1”))
45
{
46
var c= addNewContact()
47
contacts.add(c)
48
}
49
else if(s.equals(“2”)) {
50
printContacts(contacts)
51
}
52
else if(s.equals(“3”))
53
{
54
var sff=SerializableFileFactory()
55
var ret=sff.saveFile(contacts,
56
“d:/contacts.dat”)
57
if(ret==true)
58
println(“Save file successful!”)
59
else
60
println(“Save file Failed!”)
61
}
62
else if(s.equals(“4”))
63
{
64
var sff=SerializableFileFactory()
65
var data=
66
sff.openFile(“d:/contacts.dat”)
67
if(data!=null)
68
{
69
contacts=
70
data as MutableList<Contact>
71
printContacts(contacts)
72
}
73
}
74
else
75
break
76
}
77
}
78
}
79
80
Run the software to test the functions, we do the following test cases:
We enter 1 and then press the Enter key, repeat this operation until all 3
Contacts are entered:
265
File Processing
Your choice:2
100 John [email protected]
200 Peter [email protected]
300 Lucy [email protected]
1.Add new Contact
2.Print Contacts
3.Serialize Contacts
4.Deserialize Contacts
5.Exit
Your choice:3
Next, we enter 3 to serialize the contact list, result of successful file saving
notification:
Your choice:3
Save file successful!
1.Add new Contact
2.Print Contacts
3.Serialize Contacts
4.Deserialize Contacts
5.Exit
Your choice:4
266
File Processing
Your choice:4
100 John [email protected]
200 Peter [email protected]
300 Lucy [email protected]
1.Add new Contact
2.Print Contacts
3.Serialize Contacts
4.Deserialize Contacts
5.Exit
Your choice:5
So, the list of contacts has been deserialized back and output to the screen.
We choose 5 to end the software. Readers can run the software and read the
data again. We have serialized and deserialized successfully, readers apply
yourself to the specific project. In the next lesson, the book will discuss XML
File Handling in Kotlin which is very important in the process of data storage
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnSerializa
bleFileListObject.
The book will guide how to save and read data with XML File. We still use
the libraries in the JVM to handle Kotlin. The lesson focuses on modeling data
from XML through objects and vice versa. As with previous file manipulation
examples, we have the Product class with the following information in the
Listing 13.
267
File Processing
1
package tdt.com.model
2
class Product {
3
public var Code:Int=0
4
get() {return field}
5
set(value) {field=value}
6
public var Name:String=””
7
get() {return field}
8
set(value) {field=value}
9
public var UnitPrice:Double=0.0
10
get() {return field}
11
set(value) {field=value}
12
constructor()
13
constructor(code: Int, name: String,
14
unitPrice: Double) {
15
this.Code = code
16
this.Name = name
17
this.UnitPrice = unitPrice
18
}
19
override fun toString(): String {
20
return “$Code\t$Name\t$UnitPrice”
21
}
22
}
23
The Product class includes the Property Code, Name, and UnitPrice.
Getters/setters as well as other structures are defined as above.
About the XML file structure, the book wants you to save the data XML
with format as below in the Listing 14.
268
File Processing
The structure of the <Products> root tag, each element inside consists
of a <Product> tag, the Product attributes are represented by the <Code>,
<Name> and <Price> tags.
In order to save and read the XML File we have to use the following
libraries:
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import org.w3c.dom.Element
The book creates an XMLFileFactory class that has two methods for writing
XML files and reading XML files. You want to know more about XML,
you should do some extra research about XML. Please pay attention to this:
The SaveFile (data, path) function is a function that takes the Product List
data into an XML file. The ReadFile (path) function modeled back from the
XML datatype into object-oriented in Kotlin as a list of Product.
The source codes are shown in the Listing 15.
269
File Processing
1 package tdt.com.io
2 import tdt.com.model.Product
3 import java.io.File
4 import javax.xml.parsers.DocumentBuilderFactory
5 import javax.xml.transform.TransformerFactory
6 import javax.xml.transform.dom.DOMSource
7 import javax.xml.transform.stream.StreamResult
8 import org.w3c.dom.Element
9 class XMLFileFactory {
10 /**
11 * @author Tran Duy Thanh
12 * @param data: Data is Product list to be saved
13 * @param path: Storage path
14 * @return true if saved successfully, false if save fails
15 */
16 fun SaveFile(data:MutableList<Product>, path:String):Boolean
17 {
18 try
19 {
20 var docFactory = DocumentBuilderFactory.newInstance()
21 var docBuilder = docFactory.newDocumentBuilder()
22 // create document object
23 var doc = docBuilder.newDocument()
24 //create root element <Products>
25 var rootElement = doc.createElement(“Products”)
26 //add rootElement to document
27 doc.appendChild(rootElement)
28 for(product in data)
29 {
30 //create Product element <Product>
31 var productElement = doc.createElement(“Product”)
32 //create Code element <Code>
33 var codeElement=doc.createElement(“Code”)
34 codeElement.textContent=product.Code.toString()
35 //add <Code> tag into <Product> tag
36 productElement.appendChild(codeElement)
37 //create Name element <Name>
38 var nameElement=doc.createElement(“Name”)
39 nameElement.textContent=product.Name
40 //add <Name> tag into <Product> tag
41 productElement.appendChild(nameElement)
42 //create Price element <Price>
43 var priceElement=doc.createElement(“Price”)
44 priceElement.textContent=
45 product.UnitPrice.toString()
46 //add <Price> tag into <Product> tag
47 productElement.appendChild(priceElement)
48 ////add <Product> tag into <Products> tag
49 rootElement.appendChild(productElement)
270
File Processing
50
51
}
52
// write the content into xml file
53
var transformerFactory =
54
TransformerFactory.newInstance()
55
var transformer = transformerFactory.newTransformer()
56
var source = DOMSource(doc)
57
var result = StreamResult(File(path).absolutePath)
58
// Output to console for testing
59
transformer.transform(source, result)
60
return true
61
}
62
catch (ex:Exception)
63
{
64
ex.printStackTrace()
65
}
66
return false
67
}
68
/**
69
* @author TranDuy Thanh
70
* @param path:storage path to read data
71
* @return Product list MutableList
72
*/
73
fun ReadFile(path:String):MutableList<Product>
74
{
75
var data:MutableList<Product> = mutableListOf()
76
try {
77
//Get the DOM Builder Factory
78
var factory = DocumentBuilderFactory.newInstance()
79
//Get the DOM Builder
80
var builder = factory.newDocumentBuilder()
81
//Load and Parse the XML document
82
//document contains the complete XML as a Tree.
83
var xmlfile = File(path)
84
var document = builder.parse(xmlfile)
85
//Iterating the nodes and extracting the data.
86
var nodeList = document.documentElement.childNodes
87
for (i in 0..nodeList.length - 1) {
88
89
271
File Processing
90
91 //We have encountered an <Product> tag.
92 var node = nodeList.item(i)
93 if (node is Element) {
94 var product = Product()
95 var childNodes = node.getChildNodes()
96 for (j in 0..childNodes.getLength() - 1) {
97 var cNode = childNodes.item(j)
98 //Identifying the child tag of Product
99 if (cNode is Element) {
100 var content = cNode.getLastChild()
101 .getTextContent().trim()
102 when (cNode.getNodeName()) {
103 “Code” ->
104 product.Code= content.toInt()
105 “Name” ->
106 product.Name= content
107 “Price” ->
108 product.UnitPrice=
109 content.toDouble()
110 }
111 }
112 }
113 data.add(product)
114 }
115 }
116 }
117 catch (ex:Exception)
118 {
119 ex.printStackTrace()
120 }
121 return data
122 }
123 }
124
We create a main function to test writing the XML FILE, the codes are
in the Listing 16.
272
File Processing
1
2 package tdt.com.test
3 import tdt.com.io.XMLFileFactory
4 import tdt.com.model.Product
5 fun main(args: Array<String>) {
6 var data:MutableList<Product> = mutableListOf()
7 var product1=Product(1,”Coca cola”,15.5)
8 data.add(product1)
9 var product2=Product(2,”Sting”,25.0)
10 data.add(product2)
11 var product3=Product(3,”Redbull”,17.0)
12 data.add(product3)
13 var xmlff=XMLFileFactory()
14 var ret=xmlff.SaveFile(data,”d:/Productdata.xml”)
15 if(ret)
16 {
17 println(“Save text file successfully”)
18 }
19 else
20 {
21 println(“Save text file failed”)
22 }
23 }
24
The code above creates 3 Products and puts them in a MutableList, and
then passes them to the SaveFile function of the XMLFileFactory class. Run
the program, we have the following result:
273
File Processing
Apparently, the list Product object has saved successfully in XML format,
now we will call the function ReadFile to restore the list Product object from
XML, the codes are shown in the Listing 17.
274
File Processing
1
2 package tdt.com.test
3 import tdt.com.io.XMLFileFactory
4 import tdt.com.model.Product
5 fun main(args: Array<String>) {
6 var path=”d:/Productdata.xml”
7 var xmlff=XMLFileFactory()
8 var data:MutableList<Product>
9 data=xmlff.ReadFile(path)
10 for (product in data)
11 println(product)
12 }
13
We have saved and read XML File successfully, you apply yourself to
specific projects, structure XML File is how you decide. In the next lessons,
the book will discuss JSON File Handling in Kotlin which is very important
in the process of data storage. The source code can be downloaded at the
link: https://github.com/thanhtd32/kotlin/tree/main/LearnXMLFile.
Readers have known three types of file interaction: Text File, Serialize File,
XML file. Now the book is going to write about a very popular file format
that is the Json format.
JSON Format
275
File Processing
{
firstName:”Susan”,
lastName:”Happy”,
age:18,
email:”[email protected]”
}
The above JSonObject has the properties: firstName, lastName, age and
email, with their respective values.
An array object that contains many ordered children. The subword parts
are enclosed in “[]” pairs and separated by a “,”. Each child element can be
a single value like: number, string, true-false, null or another object, maybe
even an array.
276
File Processing
[
{
“Code”: “P1”,
“Name”: “DELL Inspiron 14NR”,
“Quantity”: 100,
“UnitPrice”: 2000
},
{
” Code”: “P2”,
” Name”: “HP Inspiron 113”,
“Quantity”: 130,
“UnitPrice”: 1400
}
]
Kotlin also has classes available for Json interactions, or there are many
well-known external libraries such as GSon, Klaxon etc., which make it easy
to convert Object Model to Json, and Json to Object Model vice versa.
In this lesson, the book will show how to use GSon in Kotlin to convert
between Object Model and Json. We download GSon library and reference
it to Project in your IntelliJ IDEA, the link can be downloaded at the
link: https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8
.8/.
Readers can download another GSon version at the link: https://repo1.
maven.org/maven2/com/google/code/gson/gson/.
277
File Processing
Download the gson-2.8.8.jar (about 237kb file) from the link above to the
computer. The book briefly explains how GSon works:
278
File Processing
If the Json data is a JsonAray, then for the Kotlin Model we should do the
following to conver the JsonArray to a list of KotlinModel:
The book will show the instructions so that readers can easily understand
and manipulate the GSon library. We create a project named LearnJSonFile,
and from this project, we create a directory named libs to copy gson-2.8.8.jar
library into libs. The figure 11.9 shows how to select the Directory.
279
File Processing
We define the name of the directory is “libs” and click OK, the libs
directory will be created in the project. And then we copy the gson-2.8.8.jar
file to this folder as shown in the Figure 11.
280
File Processing
Name item is default and we click OK, and readers see a change in the
way that readers see the set of GSon classes in the Figure 14.
281
File Processing
282
File Processing
writing the code to save the Course object as well as the Course list to JSon
format and vice versa. Now, we create the Course class as below in the
Listing 18.
1
2 package tdt.com.model
3 import java.io.Serializable
4 class Course: Serializable{
5 public var Id:String?=null
6 get() {return field}
7 set(value) {field=value}
8 public var Name:String?=null
9 get() {return field}
10 set(value) {field=value}
11 public var Credit:Int=0
12 get() {return field}
13 set(value) {field=value}
14 constructor()
15 constructor(Id: String?,
16 Name: String?,
17 Credit: Int) {
18 this.Id = Id
19 this.Name = Name
20 this.Credit = Credit
21 }
22 override fun toString(): String {
23 return “$Id\t$Name\t$Credit”
24 }
25 }
26
We write codes to convert the Course object into the JSon String format, we
create TestCourseToJSonString.kt and write code as the listing 19.
283
File Processing
1
2
package tdt.com.test
3
import com.google.gson.Gson
4
import tdt.com.model.Course
5
fun main(args: Array<String>) {
6
//Create a GSon object
7
var gson = Gson()
8
//create a course object
9
var course = Course()
10
course.Id=”C12”
11
course.Name=”Kotlin Language”
12
course.Credit=3
13
//convert course object to json string
14
var jsonInString = gson.toJson(course)
15
//print the course information by json string
16
println(jsonInString)
17
//print the course information by object model
18
println(course)
19
}
20
21
We see the string Json format of the course object displayed as above.
The Listing 20 shows how to convert the string Json format to the Course
object.
284
File Processing
1
2
package tdt.com.test
3
import com.google.gson.Gson
4
import tdt.com.model.Course
5
fun main(args: Array<String>) {
6
//Create a GSon object
7
var gson = Gson()
8
//create a string json:
9
var json = “{\”Id\”:\”C12\”,\”Name\”:\”Kotlin Language\”, \”Credit\”:3}”
10
//print the course information by json string
11
println(json)
12
//print the course information by object model
13
var course = gson.fromJson(json, Course::class.java)
14
println(course)
15
}
16
17
We see the Json structure and the Course object model displayed as above.
285
File Processing
1
2 package tdt.com.test
3 import com.google.gson.Gson
4 import tdt.com.model.Course
5 import java.io.FileWriter
6 fun main(args: Array<String>) {
7 //Create a GSon object
8 var gson = Gson()
9 //create a course object
10 var course = Course()
11 course.Id=”C12”
12 course.Name=”Kotlin Language”
13 course.Credit=3
14 //create a FileWriter object
15 //this is location to save the data
16 var file= FileWriter(“D:\\course.json”)
17 //call toJson to convert course to json
18 //and save this data to file
19 gson.toJson(course, file)
20 //We have to call close() method
21 file.close()
22 }
23
We run the code above and then go to the drive D to see the json file is
created, it is shown in the Figure 15.
Next, we proceed to convert the data in course.json file into Course object
model, we create a TestCourseFromJSonFile.kt and write code as the Listing 22.
286
File Processing
1
package tdt.com.test
2
import com.google.gson.Gson
3
import tdt.com.model.Course
4
import java.io.FileReader
5
fun main(args: Array<String>) {
6
//Create a GSon object
7
var gson = Gson()
8
//create a FileReader object
9
//this is location to read the data
10
var fr=FileReader(“D:\\course.json”)
11
//call fromJson method
12
//Course::class.java is syntax to convert
13
var course = gson.fromJson(fr, Course::class.java)
14
println(course)
15
}
16
We have known how to convert an object model to Json format and vice
versa. Readers can apply the technique to another projects. Source code can
be downloaded at the link: https://github.com/thanhtd32/kotlin/tree/main/
LearnJSonFile.
287
File Processing
288
File Processing
1
2
package tdt.com.io
3
import com.google.gson.Gson
4
import java.io.FileWriter
5
import java.io.FileReader
6
import com.google.gson.reflect.TypeToken
7
import tdt.com.model.Course
8
class JSonFileFactory {
9
/**
10
* @author TranDuy Thanh
11
* @param data: Data is Course list to be saved
12
* @param path: Storage path
13
* @return true if saved successfully,
14
* false if save fails
15
*/
16
fun SaveFile(data:MutableList<Course>,
17
path:String):Boolean
18
{
19
try {
20
val gs= Gson()
21
val file=FileWriter(path)
22
gs.toJson(data,file)
23
file.close()
24
return true
25
}
26
catch (ex:Exception)
27
{
28
ex.printStackTrace()
29
}
30
return false
31
}
32
/**
33
* @author TranDuy Thanh
34
* @param path:storage path to read data
35
* @return Course list MutableList
36
*/
37
fun ReadFile(path:String):MutableList<Course>
38
{
39
var data:MutableList<Course> = mutableListOf()
40
try
41
{
42
val gson = Gson()
43
var file=FileReader(path)
44
data = gson.fromJson(file,
45
object:
46
TypeToken<MutableList<Course>>()
47
{
48
}.type
49
)
50
file.close()
51
}
52
catch (ex:Exception)
53
{
54
ex.printStackTrace()
55
}
56
return data
57
}
58
}
59
60
289
File Processing
Gson helps us to simplify the storage and reading of data. This is one
of the most popular libraries used in projects, and the JSon data format is
becoming more popular, possibly more than XML File.
We create the TestCourseListToJSon.kt file with main function to convert
the list of courses to Json as the Listing 24.
1
2 package tdt.com.test
3 import tdt.com.io.JSonFileFactory
4 import tdt.com.model.Course
5 fun main(args: Array<String>) {
6 var data:MutableList<Course> = mutableListOf()
7 //create c1 course object
8 var c1=Course()
9 c1.Id=”C12”
10 c1.Name=”Kotlin Language”
11 c1.Credit=3
12 //add c1 to list
13 data.add(c1)
14 //create c2 course object
15 var c2=Course()
16 c2.Id=”C21”
17 c2.Name=”CSharp Language”
18 c2.Credit=2
19 //add c2 to list
20 data.add(c2)
21 //create c3 course object
22 var c3=Course()
23 c3.Id=”C45”
24 c3.Name=”Edge Computing”
25 c3.Credit=3
26 //add c3 to list
27 data.add(c3)
28 //create JSonFileFactory object
29 var jsff=JSonFileFactory()
30 //call SaveFile
31 var ret=jsff.SaveFile(data,”d:/courses.json”)
32 if(ret)
33 {
34 println(“Save json file successfully”)
35 }
36 else
37 {
38 println(“Save json file failed”)
39 }
40 }
41
290
File Processing
1
2 package tdt.com.test
3 import tdt.com.io.JSonFileFactory
4 import tdt.com.model.Course
5 fun main(args: Array<String>) {
6 //create courses list object
7 var courses:MutableList<Course>
8 //create JSonFileFactory object
9 var jsff= JSonFileFactory()
10 //call ReadFile method
11 courses=jsff.ReadFile(“d:/courses.json”)
12 //print all
13 for (course in courses)
14 println(course)
15 }
16
We have saved and read JSon File successfully, Readers can apply yourself
to specific projects, JSon File structure in this case it will automatically build
based on Class structure and relationship between Class that readers created.
291
File Processing
In the next lesson, the book will show how to retrieve Json data has a
complex structure, you pay attention to it.
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnJSonFileL
istObject.
In previous lesson, The book has introduced about how to use the GSon library
to save the Kotlin Model to JSon and read converting JSon to Kotlin Model. In
this lesson, the book continues to add a more complex JSon example in Kotlin,
which is to create two classes that have a Master-Detail relationship, which is
one of the most common cases in the deployment process of actual projects.
Specifically, the book will add a Student Class that has a relationship with
the Course Class: A Student has many courses, it is shown in the Figure 18.
Let’s look at how GSon creates the JSon file as well as how to restore the
Kotlin Model. The book will go directly to the programming techniques.
292
File Processing
293
File Processing
1
package tdt.com.model
2
class Course{
3
public var Id:String?=null
4
get() {return field}
5
set(value) {field=value}
6
public var Name:String?=null
7
get() {return field}
8
set(value) {field=value}
9
public var Credit:Int=0
10
get() {return field}
11
set(value) {field=value}
12
constructor()
13
constructor(Id: String?,
14
Name: String?,
15
Credit: Int) {
16
this.Id = Id
17
this.Name = Name
18
this.Credit = Credit
19
}
20
override fun toString(): String {
21
return “$Id\t$Name\t$Credit”
22
}
23
}
24
294
File Processing
1
2 package tdt.com.model
3 class Student {
4 public var Id:String? = null
5 get() {return field}
6 set(value) {field=value}
7 public var Name:String?=null
8 get() {return field}
9 set(value) {field=value}
10 public var Courses:MutableList<Course>?=null
11 get() {return field}
12 set(value) {field=value}
13 constructor()
14 {
15 Courses= mutableListOf()
16 }
17 constructor(Id: String?, Name: String?) {
18 this.Id = Id
19 this.Name = Name
20 Courses= mutableListOf()
21 }
22 //Add new course for student
23 fun addCourse(course:Course)
24 {
25 if(Courses!=null)
26 Courses!!.add(course)
27 }
28 //print all student’s courses
29 fun printAllCourse()
30 {
31 if(Courses==null)return
32 for (course in Courses!!)
33 {
34 println(course)
35 }
36 }
37 override fun toString(): String {
38 return “$Id\t$Name”
39 }
40 }
41
And then we create the JSonFileFactory class, it has the following structure
as in the Listing 28.
295
File Processing
1
2 package tdt.com.io
3 import com.google.gson.Gson
4 import java.io.FileWriter
5 import java.io.FileReader
6 import com.google.gson.reflect.TypeToken
7 import tdt.com.model.Course
8 import tdt.com.model.Student
9 class JSonFileFactory {
10 /**
11 * @author Tran Duy Thanh
12 * @param data: Data is Student list to be saved
13 * @param path: Storage path
14 * @return true if saved successfully,
15 * false if save fails
16 */
17 fun SaveFile(data:MutableList<Student>,
18 path:String):Boolean
19 {
20 try {
21 val gs= Gson()
22 val file=FileWriter(path)
23 gs.toJson(data,file)
24 file.close()
25 return true
26 }
27 catch (ex:Exception)
28 {
29 ex.printStackTrace()
30 }
31 return false
32 }
33 /**
34 * @author Tran Duy Thanh
35 * @param path:storage path to read data
36 * @return Any list MutableList
37 */
38 fun ReadFile(path:String):MutableList<Student>
39 {
40 var data:MutableList<Student>
41 data= mutableListOf()
42 try
43 {
44 val gson = Gson()
45 var file=FileReader(path)
46 data = gson.fromJson(file,
47 object:
48 TypeToken<MutableList<Student>>()
49 {
50 }.type
51 )
52 file.close()
53 }
54 catch (ex:Exception)
55 {
56 ex.printStackTrace()
57 }
58 return data
59 }
60 }
61
296
File Processing
297
File Processing
1 package tdt.com.test
2 import tdt.com.io.JSonFileFactory
3 import tdt.com.model.Course
4 import tdt.com.model.Student
5 var path=”D:/students.json”
6 var students:MutableList<Student> = mutableListOf()
7 fun main(args: Array<String>) {
8 while(true)
9 {
10 println(“1.Create Sample Data”)
11 println(“2.Print Sample Data”)
12 println(“3.Write Sample JsonData”)
13 println(“4.Read Samle JsonData”)
14 println(“5.Exit”)
15 print(“Your choice:”)
16 var s:String?= readLine()
17 if(s!=null)
18 {
19 if(s.equals(“1”))
20 {
21 createSampledata()
22 }
23 else if(s.equals(“2”)) {
24 printSampleData()
25 }
26 else if(s.equals(“3”))
27 {
28 writeSampleJsonData()
29 }
30 else if(s.equals(“4”))
31 {
32 readSampleJsonData()
33 }
34 else
35 break
36 }
37 }
38 }
39 //create sample data list
40 fun createSampledata()
41 {
42 students.clear()
43 //create Student 1
44 var st1=Student(“ID1”,”John”)
45 students.add(st1)
46 //create Student 2
47 var st2=Student(“ID2”,”Peter”)
48 students.add(st2)
49 //create Student 3
50 var st3=Student(“ID3”,”Lucy”)
51 students.add(st3)
52 //create c1 course object
53 var c1= Course(“C12”,”Kotlin Language”,3)
54 //create c2 course object
55 var c2= Course(“C21”,”CSharp Language”,2)
56 //create c3 course object
57 var c3= Course(“C45”,”Edge Computing”,3)
58 //add new courses for student
59 st1.addCourse(c1)
298
File Processing
60
61
62
st1.addCourse(c3)
63
st2.addCourse(c1)
64
st2.addCourse(c2)
65
st2.addCourse(c3)
66
st3.addCourse(c2)
67
}
68
//print all sample data
69
fun printSampleData()
70
{
71
for (student in students)
72
{
73
println(student)
74
println(“-----------------------------”)
75
for(course in student.Courses!!)
76
{
77
println(“\t$course”)
78
}
79
println(“-----------------------------”)
80
}
81
}
82
//write sample data to json format
83
fun writeSampleJsonData()
84
{
85
var jsff=JSonFileFactory()
86
var ret= jsff.SaveFile(students, path)
87
if(ret)
88
{
89
println(“Save Json file successfully”)
90
}
91
else
92
{
93
println(“Save Json file failed”)
94
}
95
}
96
//read sample json data
97
fun readSampleJsonData()
98
{
99
var jsff=JSonFileFactory()
100
students=jsff.ReadFile(path)
101
println(“Open JSon File successfully”)
102
}
103
104
105
299
File Processing
ID1 John
-----------------------------
C12 Kotlin Language 3
C45 Edge Computing 3
-----------------------------
ID2 Peter
-----------------------------
C12 Kotlin Language 3
C21 CSharp Language 2
C45 Edge Computing 3
-----------------------------
ID3 Lucy
-----------------------------
C21 CSharp Language 2
-----------------------------
And then we choose 3 to write the student list into Json file, we check
“D:/ students.json” to see the data format as in the Figure 20.
300
File Processing
Your choice:2
ID1 John
-----------------------------
C12 Kotlin Language 3
C45 Edge Computing 3
-----------------------------
ID2 Peter
-----------------------------
C12 Kotlin Language 3
C21 CSharp Language 2
C45 Edge Computing 3
-----------------------------
ID3 Lucy
-----------------------------
C21 CSharp Language 2
-----------------------------
Readers see that JSon is easier more than Text File, Serialize File, and
XML File, right to program. The JSon structure is used a lot nowadays, and
more and more developers like it. We have completed the complex case of
JSon File that is the relationship between the classes, readers apply yourself
to specific projects.
The source code can be downloaded at the link: https://
github.com/thanhtd32/kotlin/tree/main/LearnJSonFileC
omplex.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel
301
File Processing
& Isakova, 2020; Bailey et al., 2021). Additionally, Java Object Oriented
Programming book is referenced in Schild (2019).
Exercises
class Student
{
var Id:String?=null
var Name:String?=null
}
302
File Processing
(a) ois.readObject()
(b) ois.read ()
(c) ois.openObject()
(d) ois.open()
12. Write a program to write and read a list of Employees with the following
structure, using Serializable File
class Employee
{
var Id:Int=0
var Name:String?=null
var Birthday:Date? = null
}
13. Write a program to write and read a list of Assets with the following
structure, using XML File
<assets>
<asset>
<id>id1</id>
<name>asset 1</name>
</asset>
<asset>
<id>id2</id>
<name>asset 2</name>
</asset>
</assets>
14. Write a program to write and read a list of Employee with the following
the class Diagram, using JSon File
Figure 21.
303
File Processing
REFERENCES
Bailey, A., Greenhalgh, D., & Skeen, J. (2021). Kotlin Programming: The
Big Nerd Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel, B., & Isakova, S. (2020). Atomic Kotlin. Mindview, LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Jemerov & Isakova. (2017). Kotlin in Action. Manning.
Schild, H. (2019). Java the complete Reference (11th ed.). McGraw-Hill
Education.
304
305
Chapter 12
Graphic User Interface
ABSTRACT
For customers, providing interactive user interfaces is very important because
customers can only manipulate on the intuitive screen. There are many types
of interfaces provided by different programming languages and dependent
on the case that programmer used. In addition, with the development of
programming languages, it is possible to use interfaces between different
programming languages. This chapter presents graphic user interface, guides
learners on how to write classes that inherit interfaces as well as how to drag
and drop controls on the interface to get the desired interface. In this chapter,
readers will discover layout, basic controls label, button, etc. and list, table,
tree, etc. For each type of control, detailed instructions are provided, which
makes it easy for readers to grasp the theory and implement the practical
parts. The chapter also presents how to create executables for Kotlin. At the
end of the chapter, there are exercises to help readers practice user interface
handling skills.
DOI: 10.4018/978-1-6684-6687-2.ch012
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Graphic User Interface
In this lesson, the book will introduce how to design and display interfaces
using Kotiln. We create a Project named LearnGUIPart1, then we create a
GUI Form, select the GUI form as in the Figure 1.
306
Graphic User Interface
For the first time, just leave it as default as IDEA chooses. And the book
will explain the layout manager in the next lessons.
Create Bound Class: We check it, and the logic class is automatically
created for the Form name. Then click OK to create, the tool will look like
as the Figure 4.
307
Graphic User Interface
At the Figure 4, the book marked 5 areas, each section has different
functions and meanings:
Area 1: Is the organizational structure of the Class, and libraries.
HelloWorldUI.form use to design, HelloWorldUI class use to code logic.
Area 2: The Component Tree, which tells you the layout structure of the
controls on the interface, lets you drag and drop controls here.
Area 3: Properties window, which allows you to configure parameters
for the control as: Colors, letters, sizes, names ...
Area 4: The interface design, allows us to drag the control here.
Area 5: The Pallette window, which displays the list of controls (JLabel,
JTextField, JButton, JRadioButon, JCheckBox, JList, JTable, JTree…), it
allows you to drag the controls in and drop off area 4.
Now, we drag and drop few Controls in the HelloWorldUI.form like Figure 5.
308
Graphic User Interface
Drag the JLabel to drop in the Palette to the Designer area, then in the
Property area we set font and text, or another property.
By default, the program will have a JPanel layout named panel1 for us to
drag and drop and design controls on this panel.
Now, Readers observe the HelloWorldUI class that will automatically
declare the variable of this control (panel1, it comes from HelloWorldUI.
form), it is shown like in the Figure 6.
309
Graphic User Interface
Listing 1. LearnGUIPart1/HelloWorldUI.java
1
2 import javax.swing.*;
3 public class HelloWorldUI {
4 protected JPanel panel1;
5 }
6
Listing 2. LearnGUIPart1/HelloWorldKotlinUI
1
2 import javax.swing.JFrame
3 class HelloWorldKotlinUI: HelloWorldUI {
4 //create frame object for window
5 lateinit var frame: JFrame
6 constructor()
7 constructor(title:String)
8 {
9 frame = JFrame(title)
10 //set the panel1 for frame
11 //the UI from HellWorldUI.form
12 //set the panel1 for frame
13 //the UI from HellWorldUI.form
14 frame.contentPane = panel1
15 }
16 //this method uses to show the UI
17 fun showUI() {
18 //set ‘X’ corner button to close the window
19 frame.defaultCloseOperation =JFrame.EXIT_ON_CLOSE
20 //set size for window: width=500, height=300
21 frame.setSize(500, 300)
22 //set centering desktop for the window
23 frame.setLocationRelativeTo(null)
24 //show the window
25 frame.isVisible = true
26 }
27 }
28
310
Graphic User Interface
Figure 7. TestHelloWorldUI
Listing 3. LearnGUIPart1/TestHelloWorldUI
We run the program and see the GUI shows as the Figure 8.
311
Graphic User Interface
As such, the book has completed the tutorial on how to create graphic user
interface in Kotlin. Next lesson, the book will explain how to use the Window
and layout manager. Please pay proper attention to the tutorial.
The source code can be downloaded at the link: https://github.com/
thanhtd32/kotlin/tree/main/LearnGUIPart1;
The book has shown how to create the graphic user interface in Kotlin. Now,
the book will explain the JFrame, JPanel, Layout manager and common
controls such as JLabel, JTextField, JButton.
JFrame
Readers have known how to create a project with Graphic User Interface.
Now, the book will explain how the Window is created.
To create a Window, we use the JFrame class, and the Graphic is shown
as in the Figure 9.
312
Graphic User Interface
Libraries for graphic design is swing, and awt for events listener:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Method Description
JFrame() Create the window object by JFrame
title The title of the window
defaultCloseOperation= JFrame.EXIT_ON_ Set the operation that will happen by default when closes
CLOSE the window.
setSize(500, 300) set the initial size with setSize. Width = 500, height=300
setLocationRelativeTo(null) Set center the window on the screen.
isVisible = true Show the window
• Flowlayout
• Boxlayout
• Borderlayout
• CardLayout
• FormLayout
FlowLayout Manager
FlowLayout allows adding controls on the same line, when it runs out of
space, it will automatically go down the line, we can also adjust the direction
of the control’s appearance. By default, when a JPanel is instantiated, the
container class itself will have a Layout type of FlowLayout. The Figure 10
shows the Flowlayout.
313
Graphic User Interface
Listing 4. FlowLayoutManager
1
//create a JPanel object containing the interface:
2
var pn = JPanel()
3
//Set the layout for this container:
4
pn.layout = FlowLayout()
5
//create JButton, JLabel control
6
var btn1 = JButton(“JButton 1”)
7
var btn2 = JButton(“JButton 2”)
8
var btn3 = JButton(“JButton 3”)
9
var btn4 = JButton(“JButton 4”)
10
var lbl5 = JLabel(“JLabel 1”)
11
var lbl6 = JLabel(“JLabel 2”)
12
var btn5 = JButton(“JButton 5”)
13
//add the control to panel
14
pn.add(btn1)
15
pn.add(btn2)
16
pn.add(btn3)
17
pn.add(btn4)
18
pn.add(lbl5)
19
pn.add(lbl6)
20
pn.add(btn5)
21
BoxLayout Manager
314
Graphic User Interface
Listing 5. BoxLayoutManager
1
//Create a JPanel object
2
var pn = JPanel()
3
//set layout to BoxLayout
4
pn.layout = BoxLayout(pn, BoxLayout.X_AXIS)
5
//create JButton control
6
var btn1 = JButton(“JButton 1”)
7
var btn2 = JButton(“JButton 2”)
8
var btn3 = JButton(“JButton 3”)
9
var btn4 = JButton(“JButton 4”)
10
val btn5 = JButton(“JButton 5”)
11
//add the buttons to panel:
12
pn.add(btn1)
13
pn.add(btn2)
14
pn.add(btn3)
15
pn.add(btn4)
16
pn.add(btn5)
17
BorderLayout Manager
315
Graphic User Interface
Center area will fill the window, usually when putting controls JTable, JTree,
ListView, JScrollpane ... we usually put in the Center area so that it can scale
itself according to the window size to make the interface more beautiful. The
Figure 12 shows the BoxLayout manager.
Listing 6. BorderLayoutManager
1
//create JPanel object
2
var pn = JPanel()
3
//set border layout
4
pn.layout = BorderLayout()
5
//create north panel
6
var pnNorth = JPanel()
7
pnNorth.background = Color.RED
8
pn.add(pnNorth, BorderLayout.NORTH)
9
//create south panel
10
var pnSouth = JPanel()
11
pnSouth.background = Color.RED
12
pn.add(pnSouth, BorderLayout.SOUTH)
13
//create west panel
14
var pnWest = JPanel()
15
pnWest.background = Color.BLUE
16
pn.add(pnWest, BorderLayout.WEST)
17
//create east panel
18
var pnEast = JPanel()
19
pnEast.background = Color.BLUE
20
pn.add(pnEast, BorderLayout.EAST)
21
//create center panel
22
var pnCenter = JPanel()
23
pnCenter.background = Color.YELLOW
24
pn.add(pnCenter, BorderLayout.CENTER)
25
316
Graphic User Interface
CardLayout Manager
CardLayout allows to share the display position of the controls, which means
that for the same display position, we can let other controls display at different
times, by default the first added control will be displayed.
The Figure 13 shows the CardLayout manager: When the user clicks “Show
Card1”, the graphic user interface of Card1 will appear, and when the user
clicks “Show Card2”, the graphic user interface of Card2 will appear, and
they appear at the same location.
Listing 7. CardLayoutManager
1
2 var pn = JPanel()
3 pn.layout = CardLayout()
4 var pnCard1 = JPanel()
5 pnCard1.background = Color.LIGHT_GRAY
6 var pnCard2 = JPanel()
7 pnCard2.background = Color.PINK
8 pn.add(pnCard1, “mycard1”)
9 pn.add(pnCard2, “mycard2”)
10 btnShowCard1.addActionListener(ActionListener {
11 val cl = pn.layout as CardLayout
12 cl.show(pn, “mycard1”)
13 })
14
317
Graphic User Interface
GridLayout Manager
GridLayout allows to arrange controls by row and column. We often use the
GridLayout (row, column) constructor to set the number of rows and columns
when designing the graphic user interface. The Figure 14 shows how to create
a layout with 3 rows and 2 columns.
The code examples in the Kotlin language as below is shown in the Listing 8.
318
Graphic User Interface
Listing 8. GridLayoutManager
1
2
//create a JPanel object containing the interface:
3
var pn = JPanel()
4
//Set the layout for this container:
5
//3 rows, 2 columns
6
pn.layout = GridLayout(3, 2)
7
//create JButton, JLabel control
8
var btn1 = JButton(“JButton 1”)
9
var btn2 = JButton(“JButton 2”)
10
var btn3 = JButton(“JButton 3”)
11
var btn4 = JButton(“JButton 4”)
12
var btn5 = JButton(“JButton 5”)
13
var btn6 = JButton(“JButton 6”)
14
//add the control to panel
15
pn.add(btn1)
16
pn.add(btn2)
17
pn.add(btn3)
18
pn.add(btn4)
19
pn.add(btn5)
20
pn.add(btn6)
21
22
COMMON CONTROLS
In the previous lesson, the book has shown you how to create a user graphic
interface in Kotlin. Now, the book continues guide how to use the common
controls, such as JLable, JTextField, JButton and set the event for JButton,
JRadioButton, JCheckBox...
JLabel
JLabel is used to display text, image, and not editable the text.
The Table 2 shows constructors and methods of JLabel
319
Graphic User Interface
Method Description
Creates a JLabel instance with no image and with an empty string for
JLabel()
the title.
JLabel(String text) Creates a JLabel instance with the specified text.
JLabel(Icon image) Creates a JLabel instance with the specified image.
text Set/Get the text string for the label displays.
icon Set/Get the icon that the label displays.
foreground Set/Get the text color
background Set/Get the background color
JTextField
Method Description
JTextField() Constructs a new TextField.
JTextField(String text) Constructs a new TextField initialized with the specified text.
Constructs a new empty TextField with the specified number of
JTextField(int columns)
columns.
text Set/Get the text for textfield to display.
JButton
320
Graphic User Interface
Method Description
JButton() Creates a button with no set text or icon.
JButton(String text) Creates a button with text.
icon Set/Get the Icon for button
text Set/Get the text for textfield to display.
mnemonic Set/Get the shortcut key for button
1
2 btn.addActionListener(ActionListener {
3 //do something here,coding here
4 })
5
The book will continue to add an example of the user graphic interface
design using the Gridlayout manager and how to assign events to the Controls.
We create the project “QuadraticEquationUI”, the user graphic user interface
as below is shown in the Figure 15.
321
Graphic User Interface
We create Swing GUI with name “MainUI” and set the layout manager
is the GridLayout Manager, defined name is pnMain (MainUI.form is the
design layout, MainUI class is java code logic), the Figure 16 shows how to
layout for the Quadratic equation.
322
Graphic User Interface
Now we observe that the MainUI class appears these control variable
names as follows in the Listing 10.
1
2
import javax.swing.*;
3
public class MainUI {
4
private JPanel pnMain;
5
private JTextField txtA;
6
private JTextField txtB;
7
private JTextField txtC;
8
private JTextField txtResult;
9
private JButton btnCalculate;
10
private JButton btnClear;
11
private JButton btnExit;
12
}
13
14
1
2
import javax.swing.*;
3
public class MainUI {
4
protected JPanel pnMain;
5
protected JTextField txtA;
6
protected JTextField txtB;
7
protected JTextField txtC;
8
protected JTextField txtResult;
9
protected JButton btnCalculate;
10
protected JButton btnClear;
11
protected JButton btnExit;
12
}
13
14
323
Graphic User Interface
1
2 import javax.swing.JFrame
3 class MainUIKotlin: MainUI{
4 var frame: JFrame
5 constructor() {
6 frame = JFrame(“Quadratic Equation”)
7 frame.contentPane = pnMain
8 }
9 //this method uses to show the UI
10 fun showUI() {
11 //set ‘X’ corner button to close the window
12 frame.defaultCloseOperation =JFrame.EXIT_ON_CLOSE
13 //set size for window: width=300, height=260
14 frame.setSize(300, 260)
15 //set centering desktop for the window
16 frame.setLocationRelativeTo(null)
17 //show the window
18 frame.isVisible = true
19 }
20 }
21
1
fun main(args: Array<String>) {
2
var mainUI=MainUIKotlin()
3
mainUI.showUI()
4
}
5
Run the code, we get the graphic user interface as below is shown in the
Figure 18 (but without event for the Buttons).
324
Graphic User Interface
We need to create events for Buttons for Exit, Clear and Calculate button.
In the MainUIKotlin class, we modify the code.
1
constructor() {
2
frame = JFrame(“Quadratic Equation”)
3
frame.contentPane = pnMain
4
btnExit.addActionListener { System.exit(0) }
5
}
6
Similarly, we add the event for the clear Button, it is shown in the Listing 15.
325
Graphic User Interface
1
constructor() {
2
frame = JFrame(“Quadratic Equation”)
3
frame.contentPane = pnMain
4
btnExit.addActionListener { System.exit(0) }
5
btnClear.addActionListener {
6
txtA.text = ““
7
txtB.text = ““
8
txtC.text = ““
9
txtResult.text = ““
10
txtA.requestFocus()
11
}
12
}
13
1
btnCalculate.addActionListener{
2
processQuaraticEquation()
3
}
4
326
Graphic User Interface
1
private fun processQuaraticEquation() {
2
var a = txtA.text.toDouble()
3
var b = txtB.text.toDouble()
4
var c = txtC.text.toDouble()
5
if (a == 0.0) {
6
var msg = “a must be different from 0”
7
JOptionPane.showMessageDialog(null, msg)
8
}
9
if (a != 0.0) {
10
var delta = Math.pow(b, 2.0) - 4 * a * c
11
if (delta < 0)
12
txtResult.text = “No solution!”
13
else if (delta == 0.0)
14
{
15
var result= “x1=x2=” + -b / 2 * a
16
txtResult.text =result
17
}
18
else {
19
var x1 = (-b - Math.sqrt(delta)) / (2 * a)
20
var x2 = (-b + Math.sqrt(delta)) / (2 * a)
21
txtResult.text = “x1=$x1;x2=$x2”
22
}
23
}
24
}
25
Here is the full of coding for MainUIKotlin class, and the whole codes
are shown in the Listing 18.
327
Graphic User Interface
1
2 import javax.swing.JFrame
3 import javax.swing.JOptionPane
4 class MainUIKotlin: MainUI{
5 var frame: JFrame
6 constructor() {
7 frame = JFrame(“Quadratic Equation”)
8 frame.contentPane = pnMain
9 btnExit.addActionListener { System.exit(0) }
10 btnClear.addActionListener {
11 txtA.text = ““
12 txtB.text = ““
13 txtC.text = ““
14 txtResult.text = ““
15 txtA.requestFocus()
16 }
17 btnCalculate.addActionListener{
18 processQuaraticEquation()
19 }
20 }
21 private fun processQuaraticEquation() {
22 var a = txtA.text.toDouble()
23 var b = txtB.text.toDouble()
24 var c = txtC.text.toDouble()
25 if (a == 0.0) {
26 var msg = “a must be different from 0”
27 JOptionPane.showMessageDialog(null, msg)
28 }
29 if (a != 0.0) {
30 var delta = Math.pow(b, 2.0) - 4 * a * c
31 if (delta < 0)
32 txtResult.text = “No solution!”
33 else if (delta == 0.0)
34 {
35 var result= “x1=x2=” + -b / 2 * a
36 txtResult.text =result
37 }
38 else {
39 var x1 = (-b - Math.sqrt(delta)) / (2 * a)
40 var x2 = (-b + Math.sqrt(delta)) / (2 * a)
41 txtResult.text = “x1=$x1;x2=$x2”
42 }
43 }
44 }
45 //this method uses to show the UI
46 fun showUI() {
47 //set ‘X’ corner button to close the window
48 frame.defaultCloseOperation =JFrame.EXIT_ON_CLOSE
49 //set size for window: width=300, height=260
50 frame.setSize(300, 260)
51 //set centering desktop for the window
52 frame.setLocationRelativeTo(null)
53 //show the window
54 frame.isVisible = true
55 }
56 }
57
328
Graphic User Interface
Run the program, we will have the graphic user interface as above
requirements, we test some test cases in the Figure 19.
The book hascompleted the tutorial on how to create an interface in Kotlin, how
to assign events, layout the interface, use GridLayout. Next lesson, the book will
introduce the JCheckBox and JRadioButton. The source code can be downloaded
the the link: https://github.com/thanhtd32/kotlin/tree/main/QuadraticEquat
ionUI.
JCheckBox
JCheckBox can be selected or deselected, and which displays its state to the
user. By convention, any number of check boxes in a group can be selected.
The Figure 20 shows the example for using JCheckBox.
329
Graphic User Interface
Method Description
Creates an initially unselected check box button with no text, no
JCheckBox()
icon.
JCheckBox(String text) Creates an initially unselected check box with text.
isSelected Set/Get the state of the checkbox.
text Set/Get the text this component will display.
foreground Set/Get the text color
background Set/Get the background color
330
Graphic User Interface
Create the ConfirmFavoriteUI form then drag and drop the controls as
above.
pnMain is Border layout manager.
JPanel for 4 JCheckBox is Grid layout manager and we set the name for
the JCheckBox is shown in the Table 6.
331
Graphic User Interface
1
2 import javax.swing.*;
3 public class ConfirmFavoriteUI {
4 private JPanel pnMain;
5 private JCheckBox chkKotlin;
6 private JCheckBox chkPython;
7 private JCheckBox chkSharp;
8 private JCheckBox chkJava;
9 private JButton btnConfirm;
10 }
11
1
2 import javax.swing.*;
3 public class ConfirmFavoriteUI {
4 protected JPanel pnMain;
5 protected JCheckBox chkKotlin;
6 protected JCheckBox chkPython;
7 protected JCheckBox chkSharp;
8 protected JCheckBox chkJava;
9 protected JButton btnConfirm;
10 }
11
332
Graphic User Interface
1
2
import java.awt.event.ActionListener
3
import javax.swing.JFrame
4
import javax.swing.JOptionPane
5
class ConfirmFavoriteUIKotlin:ConfirmFavoriteUI {
6
var frame: JFrame
7
constructor() {
8
frame = JFrame(“Learn Checkbox”)
9
frame.contentPane = pnMain
10
btnConfirm.addActionListener(
11
ActionListener {
12
processConfirmation()
13
})
14
}
15
private fun processConfirmation() {
16
val builder = StringBuilder()
17
if (chkJava.isSelected) {
18
builder.append(chkJava.text)
19
builder.append(“\n”)
20
}
21
if (chkKotlin.isSelected) {
22
builder.append(chkKotlin.text)
23
builder.append(“\n”)
24
}
25
if (chkPython.isSelected) {
26
builder.append(chkPython.text)
27
builder.append(“\n”)
28
}
29
if (chkSharp.isSelected) {
30
builder.append(chkSharp.text)
31
builder.append(“\n”)
32
}
33
JOptionPane.showMessageDialog(null, builder)
34
}
35
//this method uses to show the UI
36
fun showUI() {
37
//set ‘X’ corner button to close the window
38
frame.defaultCloseOperation =JFrame.EXIT_ON_CLOSE
39
//set size for window: width=300, height=150
40
frame.setSize(300, 150)
41
//set centering desktop for the window
42
frame.setLocationRelativeTo(null)
43
//show the window
44
frame.isVisible = true
45
}
46
}
47
48
333
Graphic User Interface
1
fun main(args: Array<String>) {
2
var cfui=ConfirmFavoriteUIKotlin()
3
cfui.showUI()
4
}
5
All done, we run the program and test some test cases, they are shown in
the Figure 22.
JRadioButton
JRadioButton can be selected or deselected, and which displays its state to the
user. Used with a ButtonGroup object to create a group of buttons in which
only one button at a time can be selected.
The Table 7 shows Constructors and methods of JRadioButton.
334
Graphic User Interface
Method Description
Creates an initially unselected JRadioButton with no text, no
JRadioButton ()
icon.
JRadioButton(String text) Creates an initially unselected JRadioButton with text.
isSelected Set/Get the state of the checkbox.
text Set/Get the text this component will display.
foreground Set/Get the text color
background Set/Get the background color
We design the graphic user interface for project is shown in the Figure 24.
335
Graphic User Interface
336
Graphic User Interface
1
2
import javax.swing.*;
3
public class ChangeImageUI {
4
private JPanel pnMain;
5
private JRadioButton radRose;
6
private JRadioButton radOrchid;
7
private JLabel lblImage;
8
9
}
10
11
1
2
import javax.swing.*;
3
public class ChangeImageUI {
4
protected JPanel pnMain;
5
protected JRadioButton radRose;
6
protected JRadioButton radOrchid;
7
protected JLabel lblImage;
8
protected ImageIcon icon;
9
}
10
11
1
radRose.addActionListener(
2
ActionListener {
3
if (radRose.isSelected()) {
4
icon = ImageIcon(“images/rose.png”)
5
lblImage.setIcon(icon)
6
}
7
})
8
337
Graphic User Interface
To create an ImageIcon object and set the image for this Icon, we use the
command: icon = ImageIcon(“images/rose.png”).
To assign this Icon to JLabel we call the method: lblImage.setIcon(icon).
The final source code of the ChangeImageUIKotlin class, it is shown in
the Listing 26.
1
2 import java.awt.event.ActionListener
3 import javax.swing.ButtonGroup
4 import javax.swing.ImageIcon
5 import javax.swing.JFrame
6 class ChangeImageUIKotlin:ChangeImageUI{
7 var frame: JFrame
8 constructor() {
9 frame = JFrame(“Change Image- JRadioButton”)
10 frame.contentPane = pnMain
11 val bg = ButtonGroup()
12 bg.add(radRose)
13 bg.add(radOrchid)
14 //set default image for
15 icon = ImageIcon(“images/rose.png”)
16 lblImage.setIcon(icon)
17 //check if the Rose JRadioButton is checked
18 radRose.addActionListener(
19 ActionListener {
20 if (radRose.isSelected()) {
21 icon = ImageIcon(“images/rose.png”)
22 lblImage.setIcon(icon)
23 }
24 })
25 //check if the Orchid JRadioButton is checked
26 radOrchid.addActionListener(
27 ActionListener {
28 if (radOrchid.isSelected()) {
29 icon = ImageIcon(“images/orchid.png”)
30 lblImage.setIcon(icon)
31 }
32 })
33 }
34 //this method uses to show the UI
35 fun showUI() {
36 //set ‘X’ corner button to close the window
37 frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
38 //set size for window: width=500, height=300
39 frame.setSize(500, 300)
40 //set centering desktop for the window
41 frame.setLocationRelativeTo(null)
42 //show the window
43 frame.isVisible = true
44 }
45 }
46
338
Graphic User Interface
Run the program and select the JRadioButton to change the image, it is
shown in the Figure 25.
ADVANCED CONTROLS
In this part, the book continues guide how to use the advanced controls, such
as JComboBox, JList, JTable, JTree.
JComboBox
339
Graphic User Interface
editable field into which the user can type a value. Example for JComboBox
is shown in the Figure 26.
Method Description
JComboBox() Creates a JComboBox with a default data model.
void addItem(E item) Adds an item to the item list.
selectedItem Set/Get the selected item.
selectedIndex Set/Get the selected index
void removeItem(Object anObject) Removes an item from the item list.
Removes the item at anIndex This method works only if
void removeItemAt(int anIndex)
the JComboBox uses a mutable data model.
void removeAllItems() Removes all items from the item list.
void addItemListener
Adds an ItemListener.
(ItemListener aListener)
340
Graphic User Interface
We create the EmployeeUI form then drag and drop the controls as above.
pnMain is Border layout manager.
JPanel for Employee Id, Name and Gender is Grid layout manager. And
this JPanel is placed center of the pnMain. The name for controls is shown
in the Table 10.
We create the Employee kotin class as below is shown in the Listing 28.
341
Graphic User Interface
1
class Employee {
2
public var EmployeeID:String=””
3
get() {return field}
4
set(value) {field=value}
5
public var EmployeeName:String=””
6
get() {return field}
7
set(value) {field=value}
8
public var EmployeeGender=””
9
get() {return field}
10
set(value) {field=value}
11
constructor()
12
constructor(EmployeeID: String,
13
EmployeeName: String,
14
EmployeeGender: String) {
15
this.EmployeeID = EmployeeID
16
this.EmployeeName = EmployeeName
17
this.EmployeeGender = EmployeeGender
18
}
19
override fun toString(): String {
20
return “Employee ID:$EmployeeID\n” +
21
“Employee Name:$EmployeeName\n” +
22
“Employee Gender:$EmployeeGender”
23
}
24
}
25
1
2 import javax.swing.*;
3 public class EmployeeUI {
4 private JPanel pnMain;
5 private JButton btnAdd;
6 private JTextField txtEmployeeID;
7 private JTextField txtEmployeeName;
8 private JComboBox cboEmployeeGender;
9 private JButton btnConfirm;
10 }
11
342
Graphic User Interface
1
2
import javax.swing.*;
3
public class EmployeeUI {
4
protected JPanel pnMain;
5
protected JButton btnAdd;
6
protected JTextField txtEmployeeID;
7
protected JTextField txtEmployeeName;
8
protected JComboBox cboEmployeeGender;
9
protected JButton btnConfirm;
10
}
11
12
1
private fun processConfirmation() {
2
//create Employee object(Kotlin class)
3
var em = Employee()
4
em.EmployeeID = txtEmployeeID.getText()
5
em.EmployeeName = txtEmployeeName.getText()
6
//check if user chooses the item in the JCombobox
7
if (cboEmployeeGender.selectedIndex!= -1) {
8
var gender =
9
cboEmployeeGender.selectedItem as String
10
em.EmployeeGender = gender
11
}
12
JOptionPane.showMessageDialog(null, em)
13
}
14
343
Graphic User Interface
1
2
3 import java.awt.event.ActionListener
4 import javax.swing.JFrame
5 import javax.swing.JOptionPane
6 class EmployeeUIKotlin:EmployeeUI {
7 var frame: JFrame
8 constructor() {
9 frame = JFrame(“Learn JCombobox”)
10 frame.contentPane = pnMain
11 //add item for JCombobox
12 cboEmployeeGender.addItem(“Woman”)
13 cboEmployeeGender.addItem(“Man”)
14 btnConfirm.addActionListener(
15 ActionListener {
16 processConfirmation()
17 })
18 }
19 private fun processConfirmation() {
20 //create Employee object(Kotlin class)
21 var em = Employee()
22 em.EmployeeID = txtEmployeeID.getText()
23 em.EmployeeName = txtEmployeeName.getText()
24 //check if user chooses the item
25 if (cboEmployeeGender.selectedIndex!= -1) {
26 var gender =
27 cboEmployeeGender.selectedItem as String
28 em.EmployeeGender = gender
29 }
30 JOptionPane.showMessageDialog(null, em)
31 }
32 //this method uses to show the UI
33 fun showUI() {
34 //set ‘X’ corner button to close the window
35 frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
36 //set size for window: width=300, height=200
37 frame.setSize(300, 200)
38 //set centering desktop for the window
39 frame.setLocationRelativeTo(null)
40 //show the window
41 frame.isVisible = true
42 }
43 }
44
45
344
Graphic User Interface
We run the program and test some cases. It is shown in the Figure 28.
JList
JList displays a list of objects and allows the user to select one or more items.
A separate model, ListModel, maintains the contents of the list. It can display
an array or Vector of objects by using the JList constructor or call addItem
method.
The Figure 29 shows the example for using the JList.
345
Graphic User Interface
346
Graphic User Interface
Method Description
JList() Constructs a JList with an empty, read-only, model.
Constructs a JList that displays the elements in the specified
JList(E[] listData)
array.
selectedIndex Set/Get a selected index from the list.
selectedValue Set/Get a seleceted value from the list.
void setListData(E[] listData) Constructs a read-only ListModel from an array of items.
void setListData( Constructs a read-only ListModel from a Vector and calls
Vector<? extends E> listData) setModel with this model.
void setModel Sets the model that represents the contents or “value” of
(ListModel<E> model) the list.
void clearSelection() Clears the selection
void addListSelectionListener Adds a listener to the list, to be notified each time a change
(ListSelectionListener listener) to the selection occurs.
We design the graphic user interface with JListUI project name for Employee
Information as follows is shown in the Figure 30.
347
Graphic User Interface
Create the EmployeeUI form then drag and drop the controls as above.
JPanel(pnMain) is Border Layout manager.
JPanel(pnTitle) is Flow Layout manager and set it to North of the pnMain.
JPanel(pnEmployee) for Employee Id, Name and Gender is Grid layout
manager. And this JPanel is placed center of the pnMain.
JPanel(pnSouth) contains JButton add, remove and JList is Border Layout
manager, and this JPanel is set South in the pnMain.
JPanel(pnButton) is Flow Layout manager, and this JPanel is set North
of the pnSouth.
JPanel(pnListEmployee) is Border Layout manager, and this JPanel is
set Center of the pnSouth. We have to use JScrollPane with JList, and set
JScrollPane into the Center of the pnListEmployee.
The Table 12 shows the name defining for the controls.
The program allows users to enter Employee’s information, press the “Add”
button, and Empoyee information will be added in the JList.
Each time user clicks on each Employee in the JList, the details of the
Employee will be displayed again into the JTextField and JComboBox.
Pressing the “Remove” Button, it will remove Employee from the JList.
We create Employee kotin class as below is shown in the Listing 34.
348
Graphic User Interface
1
2 class Employee {
3 public var EmployeeID:String=””
4 get() {return field}
5 set(value) {field=value}
6 public var EmployeeName:String=””
7 get() {return field}
8 set(value) {field=value}
9 public var EmployeeGender=””
10 get() {return field}
11 set(value) {field=value}
12 constructor()
13 constructor(EmployeeID: String,
14 EmployeeName: String,
15 EmployeeGender: String) {
16 this.EmployeeID = EmployeeID
17 this.EmployeeName = EmployeeName
18 this.EmployeeGender = EmployeeGender
19 }
20 override fun toString(): String {
21 return “$EmployeeName”
22 }
23 }
24
1
2
import javax.swing.*;
3
public class EmployeeUI {
4
private JTextField txtEmployeeID;
5
private JTextField txtEmployeeName;
6
private JComboBox cboEmployeeGender;
7
private JButton btnAdd;
8
private JButton btnRemove;
9
private JList lstEmployee;
10
private JPanel pnMain;
11
private JPanel pnSouth;
12
private JPanel pnEmployee;
13
private JPanel pnButton;
14
private JPanel pnListEmployee;
15
private JPanel pnTitle;
16
}
17
18
349
Graphic User Interface
1
2
import javax.swing.*;
3
public class EmployeeUI {
4
protected JTextField txtEmployeeID;
5
protected JTextField txtEmployeeName;
6
protected JComboBox cboEmployeeGender;
7
protected JButton btnAdd;
8
protected JButton btnRemove;
9
protected JList lstEmployee;
10
protected JPanel pnMain;
11
protected JPanel pnSouth;
12
protected JPanel pnEmployee;
13
protected JPanel pnButton;
14
protected JPanel pnListEmployee;
15
protected JPanel pnTitle;
16
}
17
18
1
var model: DefaultListModel<Employee>
2
//assign model for JList
3
model = DefaultListModel()
4
lstEmployee.setModel(model)
5
1
private fun addEmployeeToList() {
2
var em = Employee()
3
em.EmployeeID = txtEmployeeID.text
4
em.EmployeeName = txtEmployeeName.text
5
if (cboEmployeeGender.selectedIndex != -1) {
6
var gender=cboEmployeeGender.selectedItem
7
em.EmployeeGender = gender.toString()
8
}
9
model.addElement(em)
10
}
11
350
Graphic User Interface
1
private fun removeEmployee() {
2
var obj = lstEmployee.selectedValue
3
if (obj != null) {
4
model.removeElement(obj)
5
}
6
}
7
1
private fun showDetailEmployee() {
2
var obj = lstEmployee.selectedValue
3
if (obj != null) {
4
var em = obj as Employee
5
txtEmployeeID.text = em.EmployeeID
6
txtEmployeeName.text = em.EmployeeName
7
var gender = em.EmployeeGender
8
cboEmployeeGender.selectedItem = gender
9
}
10
}
11
351
Graphic User Interface
1 import javax.swing.DefaultListModel
2 import javax.swing.JFrame
3 class EmployeeUIKotlin:EmployeeUI {
4 var frame: JFrame
5 var model: DefaultListModel<Employee>
6 constructor() {
7 frame = JFrame(“Learn JList”)
8 frame.contentPane = pnMain
9 //add item for JCombobox
10 cboEmployeeGender.addItem(“Woman”)
11 cboEmployeeGender.addItem(“Man”)
12 //assign model for JList
13 model = DefaultListModel()
14 lstEmployee.setModel(model)
15 btnAdd.addActionListener {
16 addEmployeeToList()
17 }
18 btnRemove.addActionListener {
19 removeEmployee()
20 }
21 lstEmployee.addListSelectionListener {
22 showDetailEmployee()
23 }
24 }
25 //show detail employee when user click on JList
26 private fun showDetailEmployee() {
27 var obj = lstEmployee.selectedValue
28 if (obj != null) {
29 var em = obj as Employee
352
Graphic User Interface
30
txtEmployeeID.text = em.EmployeeID
31
txtEmployeeName.text = em.EmployeeName
32
var gender = em.EmployeeGender
33
cboEmployeeGender.selectedItem = gender
34
}
35
}
36
//remove the selected employee
37
private fun removeEmployee() {
38
var obj = lstEmployee.selectedValue
39
if (obj != null) {
40
model.removeElement(obj)
41
}
42
}
43
//add a new employee into the JList
44
private fun addEmployeeToList() {
45
var em = Employee()
46
em.EmployeeID = txtEmployeeID.text
47
em.EmployeeName = txtEmployeeName.text
48
if (cboEmployeeGender.selectedIndex != -1) {
49
var gender=cboEmployeeGender.selectedItem
50
em.EmployeeGender = gender.toString()
51
}
52
model.addElement(em)
53
}
54
//this method uses to show the UI
55
fun showUI() {
56
//set ‘X’ corner button to close the window
57
frame.defaultCloseOperation = JFrame.EXIT_ON_
58
CLOSE
59
//set size for window: width=300, height=200
60
frame.setSize(300, 380)
61
//set centering desktop for the window
62
frame.setLocationRelativeTo(null)
63
//show the window
64
frame.isVisible = true
65
}
66
}
67
353
Graphic User Interface
The Figure 31 shows the Employee JList GUI, we take some test cases.
JTable
In the previous lessons, Readers already have known the graphic user interface
design as well as the event handling in Kotlin. The book continues to show
an advanced control that is JTable so that you can display list data as well to
reinforce the knowledge you have learned.
JTable is used to display and edit regular two-dimensional tables of cells.
It is shown in the Figure 32.
354
Graphic User Interface
Method Description
Constructs a default JTable that is initialized with a default
JTable() data model, a default column model, and a default selection
model.
Constructs a JTable that is initialized with dm as the data
JTable(TableModel dm)
model, a default column model, and a default selection model.
selectedRow Get the index of the first selected row, -1 if no row is selected.
Get the index of the first selected column, -1 if no column is
selectedColumn
selected.
Object getValueAt
Returns the cell value at row and column.
(int row, int column)
Adds the specified mouse listener to receive mouse events
void addMouseListener
from this component. If listener l is null, no exception is thrown
(MouseListener l)
and no action is performed.
Adds the specified key listener to receive key events from this
void addKeyListener
component. If l is null, no exception is thrown and no action is
(KeyListener l)
performed.
355
Graphic User Interface
Method Description
Constructs a DefaultTableModel which is a table
DefaultTableModel()
of zero columns and zero rows.
void addColumn(Object columnName) Adds a column to the model.
void addRow(Object[] rowData) Adds a row to the end of the model.
void addRow(Vector rowData) Adds a row to the end of the model.
columnCount Set/Get the number of columns
rowCount Set/Get the number of rows in this data table.
Returns an attribute value for the cell at row and
Object getValueAt(int row, int column)
column.
void insertRow(int r, Object[] rowData) Inserts a row at r index in the model.
void insertRow(int r, Vector rowData) Inserts a row at r index in the model.
void removeRow(int r) Removes the row at r index
Sets the object value for the cell at column and
void setValueAt(Object aValue, int row, int column)
row.
356
Graphic User Interface
We design the graphic user interface with JTableUI project name for
Employee Information as follows is shown in the Figure 33.
We create EmployeeUI and design the controls is shown in the Figure 34.
357
Graphic User Interface
Create the EmployeeUI form then drag and drop the controls as above.
JPanel(pnMain) is Border Layout manager.
JPanel(pnTitle) is Flow Layout manager and set it to North of the pnMain.
JPanel(pnEmployee) for Employee Id, Name and Gender is Grid layout
manager. And this JPanel is placed center of the pnMain.
JPanel(pnSouth) contains JButton add, remove and JList is Border Layout
manager, and this JPanel is set South in the pnMain.
JPanel(pnButton) is Flow Layout manager, and this JPanel is set North
of the pnSouth.
JPanel(pnListEmployee) is Border Layout manager, and this JPanel is set
Center of the pnSouth.
We have to use JScrollPane with JTable, and we set JScrollPane into the
Center of the pnListEmployee. We define name for controls is shown in the
Table 15.
The program allows users to enter Employee’s information, press the “Add”
button, and Empoyee information will be added in the JTable.
Each time you click on each Employee in the JTable, the details of the
Employee will be displayed again into the JTextField and JComboBox.
Pressing the “Remove” Button, it will remove Employee from the JTable.
We create Employee kotin class as below is shown in the Listing 44.
358
Graphic User Interface
1
2 class Employee {
3 public var EmployeeID:String=””
4 get() {return field}
5 set(value) {field=value}
6 public var EmployeeName:String=””
7 get() {return field}
8 set(value) {field=value}
9 public var EmployeeGender=””
10 get() {return field}
11 set(value) {field=value}
12 constructor()
13 constructor(EmployeeID: String,
14 EmployeeName: String,
15 EmployeeGender: String) {
16 this.EmployeeID = EmployeeID
17 this.EmployeeName = EmployeeName
18 this.EmployeeGender = EmployeeGender
19 }
20 override fun toString(): String {
21 return “$EmployeeName”
22 }
23 }
24
1
2 import javax.swing.*;
3 public class EmployeeUI {
4 private JPanel pnTitle;
5 private JPanel pnEmployee;
6 private JTextField txtEmployeeID;
7 private JTextField txtEmployeeName;
8 private JComboBox cboEmployeeGender;
9 private JPanel pnSouth;
10 private JPanel pnButton;
11 private JButton btnAdd;
12 private JButton btnRemove;
13 private JPanel pnListEmployee;
14 private JPanel pnMain;
15 private JTable tblEmployee;
16
17 }
18
359
Graphic User Interface
1
2
import javax.swing.*;
3
public class EmployeeUI {
4
protected JPanel pnTitle;
5
protected JPanel pnEmployee;
6
protected JTextField txtEmployeeID;
7
protected JTextField txtEmployeeName;
8
protected JComboBox cboEmployeeGender;
9
protected JPanel pnSouth;
10
protected JPanel pnButton;
11
protected JButton btnAdd;
12
protected JButton btnRemove;
13
protected JPanel pnListEmployee;
14
protected JPanel pnMain;
15
protected JTable tblEmployee;
16
}
17
18
1
var tableModel: DefaultTableModel
2
//Create the DefaultTableModel object
3
tableModel = DefaultTableModel()
4
//add 3 columns for DefaultTableModel
5
tableModel.addColumn(“Employee ID”)
6
tableModel.addColumn(“Employee Name”)
7
tableModel.addColumn(“Employee Gender”)
8
//setmodel for JTable
9
tblEmployee.setModel(tableModel)
10
We assign the event for JButton Add to insert new Employee in the JTable,
let’s see the Listing 48 how to add event and insert a new row into the JTable.
360
Graphic User Interface
1
btnAdd.addActionListener{
2
processAddNewEmployee()
3
}
4
//add new employee
5
private fun processAddNewEmployee() {
6
var id: String = txtEmployeeID.getText()
7
var name: String = txtEmployeeName.getText()
8
var gender = ““
9
if (cboEmployeeGender.selectedIndex == 0)
10
gender = “Woman”
11
else
12
gender =”Man”
13
var row = arrayOf(id, name, gender)
14
//insert new row
15
tableModel.addRow(row)
16
}
17
1
tblEmployee.addMouseListener(
2
object: MouseAdapter() {
3
override fun mousePressed(e: MouseEvent) {
4
super.mousePressed(e)
5
showDetailEmployee()
6
}
7
})
8
//Show detail employee information
9
private fun showDetailEmployee() {
10
if (tblEmployee.selectedRow == -1)
11
return
12
var row: Int = tblEmployee.selectedRow
13
var id = tblEmployee.getValueAt(row, 0)
14
var name = tblEmployee.getValueAt(row, 1)
15
var gender = tblEmployee.getValueAt(row, 2)
16
txtEmployeeID.setText(id.toString())
17
txtEmployeeName.setText(name.toString())
18
cboEmployeeGender.
19
setSelectedItem(gender.toString())
20
}
21
361
Graphic User Interface
1
btnRemove.addActionListener{
2
processRemoveEmployee()
3
}
4
//remove employee from the JTable
5
private fun processRemoveEmployee() {
6
if (tblEmployee.selectedRow == -1)
7
return
8
var row: Int = tblEmployee.selectedRow
9
tableModel.removeRow(row)
10
}
11
1 import java.awt.event.MouseAdapter
2 import java.awt.event.MouseEvent
3 import javax.swing.JFrame
4 import javax.swing.table.DefaultTableModel
5 class EmployeeUIKotlin: EmployeeUI {
6 var tableModel: DefaultTableModel
7 var frame: JFrame
8 constructor() {
9 frame = JFrame(“Learn JTable”)
10 frame.contentPane = pnMain
11 //add item for JCombobox
12 cboEmployeeGender.addItem(“Woman”)
13 cboEmployeeGender.addItem(“Man”)
14 //Create the DefaultTableModel object
15 tableModel = DefaultTableModel()
16 //add 3 columns for DefaultTableModel
17 tableModel.addColumn(“Employee ID”)
18 tableModel.addColumn(“Employee Name”)
19 tableModel.addColumn(“Employee Gender”)
20 //setmodel for JTable
21 tblEmployee.setModel(tableModel)
22 btnAdd.addActionListener{
23 processAddNewEmployee()
24 }
25 tblEmployee.addMouseListener(
26 object: MouseAdapter() {
27 override fun mousePressed(e: MouseEvent) {
28 super.mousePressed(e)
29 showDetailEmployee()
30 }
31 })
32 btnRemove.addActionListener{
33 processRemoveEmployee()
34 }
35 }
36 //remove employee from the JTable
37 private fun processRemoveEmployee() {
38 if (tblEmployee.selectedRow == -1)
39 return
362
Graphic User Interface
40
41 var row: Int = tblEmployee.selectedRow
42 tableModel.removeRow(row)
43 }
44 //Show detail employee information
45 private fun showDetailEmployee() {
46 if (tblEmployee.selectedRow == -1)
47 return
48 var row: Int = tblEmployee.selectedRow
49 var id = tblEmployee.getValueAt(row, 0)
50 var name = tblEmployee.getValueAt(row, 1)
51 var gender = tblEmployee.getValueAt(row, 2)
52 txtEmployeeID.setText(id.toString())
53 txtEmployeeName.setText(name.toString())
54 cboEmployeeGender.
55 setSelectedItem(gender.toString())
56 }
57 //add new employee
58 private fun processAddNewEmployee() {
59 var id: String = txtEmployeeID.getText()
60 var name: String = txtEmployeeName.getText()
61 var gender = ““
62 if (cboEmployeeGender.selectedIndex == 0)
63 gender = “Woman”
64 else
65 gender =”Man”
66 var row = arrayOf(id, name, gender)
67 //insert new row
68 tableModel.addRow(row)
69 }
70 //this method uses to show the UI
71 fun showUI() {
72 //set ‘X’ corner button to close the window
73 frame.defaultCloseOperation = JFrame.EXIT_ON_
74 CLOSE
75 //set size for window: width=450, height=430
76 frame.setSize(450, 430)
77 //set centering desktop for the window
78 frame.setLocationRelativeTo(null)
79 //show the window
80 frame.isVisible = true
81 }
82 }
83
Finally, The Listing 52, we create TestEmployeeUI.kt and write the main
function to run the program.
363
Graphic User Interface
We run program and test some cases is shown in the Figure 35.
364
Graphic User Interface
JTree
This is the last lesson for Graphic User Interface. The book will introduce how
to create a JTree, get the DefaultMutableTreeNode into JTree Especially use
Object-oriented programming to put data on this tree, as well as know how
to handle events when users click on each node on the tree. JTree displays a
set of hierarchical data as an outline is shown in the Figure 36.
365
Graphic User Interface
Method Description
JTree() Returns a JTree with a sample model.
Returns an instance of JTree which displays the root node.
JTree(TreeModel newModel)
And the tree is created using the specified data model.
Ensures that the node identified by the specified path is
void collapsePath(TreePath path)
collapsed and viewable.
void collapseRow(int row) Ensures that the node in the specified row is collapsed.
Ensures that the node identified by the specified path is
void expandPath(TreePath path)
expanded and viewable.
Ensures that the node in the specified row is expanded and
void expandRow(int row)
viewable.
lastSelectedPathComponent Returns the last path component of the selected path.
Method Description
Creates a tree node that has no parent and no children, but
DefaultMutableTreeNode()
which allows children.
DefaultMutableTreeNode(Object Creates a tree node with no parent, no children, but which
userObject) allows children, and initializes it with the specified user object.
Removes newChild from its parent and makes it a child of this
void add(MutableTreeNode newChild)
node by adding it to the end of this node’s child array.
Returns the number of levels above this node. The distance
level
from the root to this node.
userObject Set/Get user object.
parent Returns this node’s parent or null if this node has no parent.
Removes the child at the specified index from this node’s
void remove(int childIndex)
children and sets that node’s parent to null.
366
Graphic User Interface
1
//Create a root node
2
var root = DefaultMutableTreeNode(“JTree”)
3
//Create a Tree
4
var tree = JTree(root)
5
//create Colors node
6
var colorsNode = DefaultMutableTreeNode(“colors”)
7
root.add(colorsNode)
8
//create blue node
9
var blueNode = DefaultMutableTreeNode(“blue”)
10
colorsNode.add(blueNode)
11
//create violetNode node
12
var violetNode = DefaultMutableTreeNode(“violet”)
13
colorsNode.add(violetNode)
14
//create Sports node
15
var sportsNode = DefaultMutableTreeNode(“sports”)
16
root.add(sportsNode)
17
//create soccer node
18
var soccerNode = DefaultMutableTreeNode(“soccer”)
19
sportsNode.add(soccerNode)
20
//create Food node
21
var foodNode = DefaultMutableTreeNode(“food”)
22
root.add(foodNode)
23
The Listing 54 illustrates how to assign events when user selects Nodes
on JTree.
1
tree.addMouseListener(object: MouseListener {
2
override fun mouseReleased(e: MouseEvent?) {}
3
override fun mousePressed(e: MouseEvent?) {}
4
override fun mouseExited(e: MouseEvent?) {}
5
override fun mouseEntered(e: MouseEvent?) {}
6
override fun mouseClicked(e: MouseEvent?) {
7
//get the selected node
8
var obj = tree.lastSelectedPathComponent
9
var selectedNode = obj as DefaultMutableTreeNode
10
//process selectedNode
11
}
12
})
13
367
Graphic User Interface
1
//Remove all nodes in the tree
2
var model = tvDemo.model
3
as DefaultTreeModel
4
var root = model.root
5
as DefaultMutableTreeNode
6
root.removeAllChildren()
7
model.reload()
8
model.setRoot(null)
9
//create the root in the tree
10
root = DefaultMutableTreeNode(“JTree”)
11
model.setRoot(root)
12
And we add the DemoJTreeUI form then drag and drop the controls as
above.
JPanel(pnMain) is Border Layout manager.
JPanel(pnWest) is Flow Layout manager and set it to West of the pnMain.
JPanel(pnNorth) for JTextField and Buttons is Flow layout manager. And
this JPanel is placed North of the pnMain.
JPanel(pnCenter) contains JTree is Border Layout manager, and this JPanel
is set Center in the pnMain.
We have to use JScrollPane with JTree, and we set JScrollPane into the
Center of the pnCenter.
368
Graphic User Interface
Table 18.
1
import javax.swing.*;
2
public class DemoJTreeUI {
3
private JPanel pnMain;
4
private JTree tvDemo;
5
private JTextField txtValue;
6
private JButton btnAddRoot;
7
private JButton btnAddChild;
8
private JButton btnRemove;
9
private JButton btnExpand;
10
private JButton btnCollapse;
11
private JPanel pnWest;
12
private JPanel pnNorth;
13
private JPanel pnCenter;
14
}
15
369
Graphic User Interface
1
2 import javax.swing.*;
3 public class DemoJTreeUI {
4 protected JPanel pnMain;
5 protected JTree tvDemo;
6 protected JTextField txtValue;
7 protected JButton btnAddRoot;
8 protected JButton btnAddChild;
9 protected JButton btnRemove;
10 protected JButton btnExpand;
11 protected JButton btnCollapse;
12 protected JPanel pnWest;
13 protected JPanel pnNorth;
14 protected JPanel pnCenter;
15 }
16
1
//Remove all nodes in the tree
2
var model = tvDemo.model as DefaultTreeModel
3
var root = model.root as DefaultMutableTreeNode
4
root.removeAllChildren()
5
model.reload()
6
model.setRoot(null)
7
1 btnAddRoot.addActionListener {
2 addRoot()
3 }
4 //add a root
5 private fun addRoot() {
6 var model = tvDemo.model as DefaultTreeModel
7 var root: DefaultMutableTreeNode
8 var value = txtValue.text
9 root = DefaultMutableTreeNode(value)
10 model.setRoot(root)
11 }
370
Graphic User Interface
To add a Child Node into the selected Node, we add event for btnAddChild
and call the addChild() method as follows is shown in the Listing 60.
1
//add a new node
2
private fun addChild() {
3
//get the selected node
4
var obj = tvDemo.lastSelectedPathComponent
5
if(obj == null)
6
return
7
var selectedNode = obj as DefaultMutableTreeNode
8
//create a new Node:
9
var value = txtValue.text
10
var childNode = DefaultMutableTreeNode(value)
11
selectedNode.add(childNode)
12
//update the UI
13
tvDemo.updateUI()
14
}
15
To remove the selected Node, we add event for btnRemove and program
it as follows is shown in the Listing 61.
1
btnRemove.addActionListener { removeNode() }
2
//remove selected node
3
private fun removeNode() {
4
var obj = tvDemo.lastSelectedPathComponent
5
if(obj == null)
6
return
7
var model = tvDemo.model as DefaultTreeModel
8
var node = obj as DefaultMutableTreeNode
9
if (node.parent != null) {
10
model.removeNodeFromParent(node)
11
} else {
12
//remove the Root
13
var root = model.root as DefaultMutableTreeNode
14
root.removeAllChildren()
15
model.reload()
16
model.setRoot(null)
17
}
18
}
19
In case of deleting Node from JTree, we need to check that Node is Root
Node or not. If it is the root node, we delete all nodes in the tree. If it is not
the root node, we will remove selected node from the Parent node.
371
Graphic User Interface
With the expanding all the nodes in the JTree, we add event for btnExpand
as program below is shown in the Listing 62.
1
btnExpand.addActionListener { expandAll() }
2
//expand all nodes
3
fun expandAll() {
4
var row = 0
5
while (row < tvDemo.rowCount) {
6
tvDemo.expandRow(row)
7
row++
8
}
9
}
10
And the last one, with the collapsing all the nodes in the JTree, we add
event for btnCollapse as program below is shown in the Listing 63.
1
btnCollapse.addActionListener { collapseAll() }
2
//collapse all nodes
3
private fun collapseAll() {
4
var row = 0
5
while (row < tvDemo.rowCount) {
6
tvDemo.collapseRow(row)
7
row++
8
}
9
}
10
372
Graphic User Interface
1 import javax.swing.JFrame
2 import javax.swing.tree.DefaultMutableTreeNode
3 import javax.swing.tree.DefaultTreeModel
4 class DemoJTreeUIKotlin:DemoJTreeUI {
5 var frame: JFrame
6 constructor() {
7 frame = JFrame(“Learn JTree”)
8 frame.contentPane = pnMain
9 //Remove all nodes in the tree
10 var model = tvDemo.model as DefaultTreeModel
11 var root = model.root as DefaultMutableTreeNode
12 root.removeAllChildren()
13 model.reload()
14 model.setRoot(null)
15 btnAddRoot.addActionListener {
16 addRoot()
17 }
18 btnAddChild.addActionListener { addChild() }
19 btnRemove.addActionListener { removeNode() }
20 btnExpand.addActionListener { expandAll() }
21 btnCollapse.addActionListener { collapseAll() }
22 }
23 //collapse all nodes
24 private fun collapseAll() {
25 var row = 0
26 while (row < tvDemo.rowCount) {
27 tvDemo.collapseRow(row)
28 row++
29 }
30 }
31 //expand all nodes
32 fun expandAll() {
33 var row = 0
34 while (row < tvDemo.rowCount) {
35 tvDemo.expandRow(row)
36 row++
37 }
38 }
39 //remove selected node
40 private fun removeNode() {
41 var obj = tvDemo.lastSelectedPathComponent
42 if(obj == null)
43 return
44 var model = tvDemo.model as DefaultTreeModel
45 var node = obj as DefaultMutableTreeNode
46 if (node.parent != null) {
47 model.removeNodeFromParent(node)
48 } else {
49 //remove the Root
50 var root = model.root as
51 DefaultMutableTreeNode
52 root.removeAllChildren()
53 model.reload()
54 model.setRoot(null)
55 }
56 }
57 //add a new node
58 private fun addChild() {
59 //get the selected node
373
Graphic User Interface
60
61
62
63 var obj = tvDemo.lastSelectedPathComponent
64 if(obj == null)
65 return
66 var selectedNode = obj as
67 DefaultMutableTreeNode
68 //create a new Node:
69 var value = txtValue.text
70 var childNode = DefaultMutableTreeNode(value)
71 selectedNode.add(childNode)
72 //update the UI
73 tvDemo.updateUI()
74 }
75 //add a root
76 private fun addRoot() {
77 var model = tvDemo.model as DefaultTreeModel
78 var root: DefaultMutableTreeNode
79 var value = txtValue.text
80 root = DefaultMutableTreeNode(value)
81 model.setRoot(root)
82 }
83 //this method uses to show the UI
84 fun showUI() {
85 //set ‘X’ corner button to close the window
86 frame.defaultCloseOperation = JFrame.EXIT_ON_
87 CLOSE
88 //set size for window: width=450, height=430
89 frame.setSize(450, 430)
90 //set centering desktop for the window
91 frame.setLocationRelativeTo(null)
92 //show the window
93 frame.isVisible = true
94 }
95 }
96
97
98
374
Graphic User Interface
Thus, the book has completed the knowledge related to Kotlin, including data
types, variable declarations, conditional statement, loops, functions, strings,
arrays, lists, object-oriented, lamda expressions, file handling, graphic user
interface… in this lesson, the book will show how to package the software
into an executable file.
IntelliJ IDEA provides us with the Tool to package software into executable
file, which is so simple that we do not need to even think of it. Let’s begin:
Step 1: Open a project, such as JTreeUI in the previous lesson.
Readers make sure that the project has file TestDemoJTreeUI.kt with main
method is shown in the Listing 66.
1
fun main(args: Array<String>) {
2
var dmtui=DemoJTreeUIKotlin()
3
dmtui.showUI()
4
}
5
375
Graphic User Interface
Step 3: Select artifacts / click on the + marker / select JAR / select From
Modules with dependencies is shown in the Figure 39.
After choose “From modules with dependencies…”, the screen “Create JAR
from Modules” will show and asks for the Main Class appears, see Figure 40.
376
Graphic User Interface
We click on the Main Class button and Choose the main class, it is shown
in the Figure 41.
377
Graphic User Interface
Readers can choose TestDemoJTreeUIkt, then click OK, the main class
is shown in the Figure 42.
378
Graphic User Interface
379
Graphic User Interface
Item 1 is the jar name created; item 2 is where the jar is stored. Select OK
to return to the main screen. We select Build menu and then choose Build
Artifacts…is shown in the Figure 44.
We choose the action Build in the Build Artifact and wait for executing
the jar file output, it is shown in the Figure 45.
380
Graphic User Interface
We choose the action Build in the Build Artifact and wait for executing the
jar file output. When the compilation is done, we see the artifacts directory
as below is shown in the Figure 46.
381
Graphic User Interface
We have completed the steps to create the jar file in Intellij IDEA. Readers
try to learn the programming language well, please train yourself to have
more knowledge of the technology. To learn programming well, readers have
to work hard, learn day by day and practice a lot.
Readers can read more explanations of the conditional structure in the
authors’ books (Jemerov et al., 2017; Griffiths & Griffiths, 2019; Eckel
& Isakova, 2020; Bailey et al., 2021). Additional Java Object Oriented
Programming book is referenced (Schild, 2019).
382
Graphic User Interface
EXERCISES
Figure 49.
383
Graphic User Interface
Figure 50.
Table 19.
Figure 51.
Figure 52.
385
Graphic User Interface
12. Write a Student management program like the interface below. A Student
includes: ID, name, gender and grade.
Figure 53.
386
Graphic User Interface
Figure 54.
◦◦ The list of categories is displayed into the JList, each time the
Category is selected, the product list of the category will be
displayed in the JTable.
◦◦ Clicking on JTable will display product details down to the section
below.
◦◦ Click “Clear”: Clear data in the JTextField.
◦◦ Click “Save”: Save the product to the selected category.
◦◦ Click “Remove”: Remove the product from the catalog.
◦◦ Right-click on JList: Display Popup menu with 3 items: Add new
Catalog, View detail CataLog, Delete Catalog.
▪▪ Add New Catalog: Open a Window to create a new Catalog.
▪▪ View Detail Catalog: Open detail information of selected
Catalog.
▪▪ Delete Catalog: Remove selected Catalog.
387
Graphic User Interface
Figure 55.
Figure 56.
388
Graphic User Interface
Figure 57.
389
Graphic User Interface
Figure 58.
◦◦ Next Button: Clear data in input fields, and focus on input field
for Product ID.
◦◦ Remove Button: Removes the currently selected Product from
the table.
◦◦ Table: Displays a list of Products when there is a change, each
time you click on a line, display product details in the details
section.
◦◦ Menus: Provide many options to save files and read files in
different formats (Text file, Serialize file, XML file and Json File).
390
Graphic User Interface
Figure 59 shows the functions for saving data in different file formats:
Figure 59.
Figure 60 illustrates the functions that read data from different file formats:
391
Graphic User Interface
Figure 60.
392
Graphic User Interface
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Eckel & Isakova. (2020). Atomic Kotlin. Mindview LLC.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Jemerov & Isakova. (2017). Kotlin in Action. Manning.
Schild, H. (2019). Java the complete Reference (11th ed.). McGraw-Hill
Education.
393
394
Chapter 13
Vert.X for Kotlin Restful API
ABSTRACT
Kotlin as well as other programming languages can be applied to writing service
APIs. This chapter presents a new framework called Vert.X. It is considered
as one of the powerful frameworks. It can support the implementation of
many services including Restful API. Kotlin is used as the main programming
language of Android mobile. When deploying Mobile, Restful API is used
to interact with data on the server, so how to create Restful APIs is very
important. Using Vert.X will help programmers save a lot of time, and Vert.X
is considered to be very optimal when deploying services. This chapter will
demonstrate the knowledge of how to build and deploy Restful APIs using
Vert.X and demonstrate how to write code in Kotlin to call these APIs and
how Postman platform interacts the API. This chapter includes brief of Restful
API, overview Vert.X, creating Restful API by Kotlin in Vert.X, calling API
in Postman, and authentication for Restful API. At the end of the chapter,
there are exercises to help readers improve their programming skills using
Vert.X to create Restful API.
DOI: 10.4018/978-1-6684-6687-2.ch013
Copyright © 2023, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Vert.X for Kotlin Restful API
In this section, we briefly introduce Restful API, its benefits, structure and
working mechanism.
Web developers often refer to the REST principle and RESTful data structure
because it is a very important part of the development of web applications.
RESTful API is a standard used in the design of APIs for web applications
to facilitate resource management. It focuses on system resources (text files,
images, audio, video, or dynamic data, etc.), including resource states that
are formatted and transmitted over HTTP or HTTPs.
Web Services as well as Restful API have several benefits such as:
395
Vert.X for Kotlin Restful API
Figure 1 illustrates the benefits of Restful API, we only need to build the
API once, from which the different platforms can access it without having to
rewrite it. Thus, it reduces labor and financial costs to implement the project,
making the project more efficient.
Structures of Restful
Rest API when designed will have many methods, mainly including GET,
POST, PUT and DELETE.
396
Vert.X for Kotlin Restful API
REST works mainly on the HTTP protocol. The above basic operations will
use their own HTTP methods (CRUD method).
HTTP GET (SELECT): Returns a Resource or a list of Resources. As
GET requests do not change the resource’s state, these are said to be safe
methods. if the resource is found on the server, then it must return HTTP
response code 200 (OK) or 404 if the resource is NOT found on the server.
And if GET API is not correctly formed then the server will return the HTTP
response code 400 (BAD REQUEST).
Example URIs of HTTP GET.
397
Vert.X for Kotlin Restful API
HTTP PUT (UPDATE): Update information for Resource (if the resource
does not exist, then API may decide to create a new resource or not). If a new
resource has been created by the PUT API, the HTTP response code should
be returned 201 (Created). If an existing resource is modified, either the 200
(OK) or 204 (No Content) response codes should be returned.
What is the difference between the HTTP POST and HTTP PUT APIs?
HTTP POST requests are made on resource collections, whereas HTTP PUT
requests are made on a single resource.
Example URIs of HTTP PUT.
398
Vert.X for Kotlin Restful API
Figure 3 shows how Restful API works. From the client, the Rest/HTTP
libraries will be referenced and invoked APIs, the Server will receive these
requests and process the data and then return the result to the client through
the APIs. The JSon data structure below illustrates a return result of the GET
function.
{
“status_code”: 200,
“data”: [
{
“id”: 1,
“name”: “john”,
“age”: 20
},
{
“id”: 2,
“name”: “peter”,
“age”: 25
}
]
}
OVERVIEW VERT.X
399
Vert.X for Kotlin Restful API
Vert.X – We can easily build and use any component or library we want.
Vert.X runs on top of the JVM – the Java Virtual Machine – allowing we
to test our code and scale it instantly. So, we need to install JDK first.
Vert.X supports many different types of programming, including Back End
programming support writing extremely good APIs. There is also extended
support for building MicroService applications.
Vert.X – used by many major technology companies in the world: Vmware,
Bosch, Cyannogen, Faunhofer, Redhat, Ticketmaster, Tesco, Swiss Post...
400
Vert.X for Kotlin Restful API
Verticle
401
Vert.X for Kotlin Restful API
Event Bus
Event bus is the main tool by which different verticles can communicate
asynchronously.
402
Vert.X for Kotlin Restful API
There is a single event bus instance for every Vert.x instance and it is
obtained using the method eventBus.
The event bus allows different parts of your application to communicate
with each other, irrespective of what language they are written in, and whether
they’re in the same Vert.x instance, or in a different Vert.x instance.
In these sections below, we will demonstrate how to embed the Vert.X library
in the application, create a website that listens on port 8080, How to build
and deploy a Verticle in Vert.X, interactive HTTP GET, HTTP POST, HTTP
PUT and HTTP DELETE, as well as how to use Postman to test these APIs.
To use Vert.X, from IntelliJ IDEA software, create a new Gradle project,
select Kotlin/JVM as shown in Figure 8.
403
Vert.X for Kotlin Restful API
Press Next button and create project name is “HelloVertX”, The project
will be created as shown in Figure 9.
404
Vert.X for Kotlin Restful API
dependencies {
implementation “org.jetbrains.kotlin:kotlin-stdlib”
implementation ‘io.vertx:vertx-web:4.2.6’
}
Then, in the kotlin directory, we create a Kotlin file with the name TestVerx.
kt and write the code as shown in Figure 11 to create a website running on
port 8080 using Vert.X.
405
Vert.X for Kotlin Restful API
Table 1.
406
Vert.X for Kotlin Restful API
command line 14, the program starts to initialize a web service on port 8080
through the listen() function..
The above program will create a website running on port 8080 and the
content displayed is “Hello VertX Kotlin”.
To run the program, click on the blue triangle icon in front of main/ then
select Run ‘TestVertXKt’. Wait for the program to compile, then open the
browser to see the results.
407
Vert.X for Kotlin Restful API
dependencies {
implementation “org.jetbrains.kotlin:kotlin-stdlib”
implementation ‘io.vertx:vertx-web:4.2.6’
implementation group: ‘com.google.code.gson’, name: ‘gson’,
version: ‘2.9.0’
}
408
Vert.X for Kotlin Restful API
Table 2.
When activating Verticle, the start function will be executed, the details of
the code will be presented in the next pages. In this example we will return a
list of courses, so add a listOfCourses method as shown in Table 3.
Table 3.
409
Vert.X for Kotlin Restful API
toJson(courses) function. And this Json string will be returned to the client
when calling the API. In the putHeader method of the Respone object, the
content-type is application/json, so the data will be in Json format. In addition,
we can replace it with XML.
Suppose we want to create API at URI /api/courses to see the entire list
of courses, in the start function, we declare like Table 4, /api/courses will
be passed to the Router object, then the listOfCourses function will invoked
in the handler.
Table 4.
Router object will receive requests from HttpServer and is responsible for
routing and creating API Methods. There are many methods provided by Router.
(Get–>HttpGet), (Post–>HttpPost), (Put–>HttpPut), (Delete–>HttpDelete).
RoutingContext is used to handle requests in Vert.x-Web, each
RoutingContext object will be created corresponding to a request Handler (can
be get, post, put, delete ...). RoutingContext is used to access HttpServerRequest
and HttpServerResponse to get data from the Client and output data back
to the Client. In addition, it also helps us to access: Session, cookies, body.
Then the router object will be passed to initialize on port 8080. If the
execution is successful, the complete() function will be executed, otherwise
the fail function will be executed.
410
Vert.X for Kotlin Restful API
Table 5.
When the user invokes the API it will look like http://localhost:8080/api/
courses
We have the full code of CourseVerticle as in Table 6.
411
Vert.X for Kotlin Restful API
Table 6.
412
Vert.X for Kotlin Restful API
Table 7.
After the program compiles and executes Verticle, we open the browser
and call the API http://localhost:8080/api/courses, we have the result as
shown in Figure 16.
413
Vert.X for Kotlin Restful API
Observing the above output, we see a Json array of strings that are the
course names returned when calling the API. This JSon string is handled by
GSon, we can return more complex structures, it will be covered in the next
sections.
The source code of CourseVerticle Project can be downloaded at the link
https://github.com/thanhtd32/kotlin/tree/main/CourseVerticle
414
Vert.X for Kotlin Restful API
The Product class is used to create a structure for the product, including
attributes id, name, quantity, and unit price. This class is demonstrated in
Table 8.
Table 8.
415
Vert.X for Kotlin Restful API
Table 9.
Table 10.
416
Vert.X for Kotlin Restful API
Table 11.
417
Vert.X for Kotlin Restful API
Table 12.
418
Vert.X for Kotlin Restful API
Table 13.
Then we proceed to execute the main function, for the GET API we can
test it on a web browser or on postman, uri http://localhost:8080/api/products
We can check the API products on the Postman, it is shown in the Figure 19.
419
Vert.X for Kotlin Restful API
Step 1, we choose GET method, step 2 we enter the API products, step
3 we click Send button, and in the step 4 we will see the result is returned
from the server. The result is the JSonArray of Product.
The source code of ProductRestful Project can be downloaded at the link
https://github.com/thanhtd32/kotlin/tree/main/ProductRestful.
We continue to add an API to get a list of products but allow to sort by unit
price ascending or descending, the parameter is passed to the program to
automatically sort. We add a function getsortedProducts as in the Table 14.
420
Vert.X for Kotlin Restful API
Table 14.
Thus, the input parameter is [sort], if sort is desc, then sort products by
descending unit price (sortByDescending), if sort is asc, then sort products
by ascending unit price (sortBy).
Edit the start function of ProductVerticle class to create a sortedproducts
API, it is shown in Tabl3 15.
421
Vert.X for Kotlin Restful API
Table 15.
Command line 4 and command line 6 above are modified to create the
api/products and api/sortedproducts APIs. The Figure 20 shows how to call
sorted products API.
Step 1, we choose the Get method, step 2 we enter the API http://
localhost:8080/api/sortedproducts, step 3, in the params tab, we enter sort in
422
Vert.X for Kotlin Restful API
the KEY column, asc or desc in the VALUE column. Step 4 we click send
button, and the sorted list of the Product will return in the step 5.
We have known how to use HTTP GET to create APIs that get list of objects
as well as sort objects by parameter. In this section we will use HTTP GET
to create an API that queries an object when its id is known. We add code
for getOneProduct function in ProductVerticle class as in Table 16.
Table 16.
The function firstOrNull will return the Product if the id is existed and it
will return null if id is not existed.
The getOneProduct function will receive an id to query whether any Product
has the id as passed or not. The syntax http://localhost:8080/api/products/1,
means get Products with id equal to 1.
The start function of ProductVerticle will be added to getOneProduct as
shown in Table 17.
423
Vert.X for Kotlin Restful API
Table 17.
424
Vert.X for Kotlin Restful API
In the Figure 21, we test the API with api/products/{id} format. http://
localhost:8080/api/products/3 it means, it will return the detail of the Product
with id=3. We can try with many different ids, even those that do not exist
to check the API’s return is correct or not.
In the previous section, we learned to create Restful API HTTP GETs to get
a list of data, sort the list, and view object details. In this article, we use the
POST method to add new data to the Server. In this section, the document
is using In-Memory Data. Store Product list in ArrayList. We can use many
different types of databases for storage, such as MongoDB, MySQL, Microsoft
SQL Server.
The Figure 22 illustrates how to convert between Kotlin Model Class and
JSon Object Data. In the case of HTTP POST, we will pass to the Server a
JsonObject with the structure of a Product as described. The program will
convert this JSonObject to Kotlin Model Class to save the data.
425
Vert.X for Kotlin Restful API
Table 18.
router.route(“/api/products*”).handler(BodyHandler.create());
router.post(“/api/products”).handler(this::insertNewProduct);
The first command allows to receive data from the client sent via the
Body tag, the second command helps to register the API /api/products with
the POST method.
Table 19 shows the code details of the start function in the ProductVerticle
class.
426
Vert.X for Kotlin Restful API
Table 19.
Then we proceed to run the main function in the RunVerticle.kt file, then
use Postman to test the HTTP POST API function, it shows in the Figure 23.
427
Vert.X for Kotlin Restful API
{
“id”: 8,
“name”: “TH True Milk”,
“quantity”: 4,
“unitPrice”: 28.0
}
428
Vert.X for Kotlin Restful API
429
Vert.X for Kotlin Restful API
The data of the product that we want to send to the Server to add a new one
will have the JSonObject format which is a string. When on the Server, the
program will use Gson to convert this Json string into a Kotlin Model class.
Once we have a model class, everything is considered complete, because we
can arbitrarily process data on the object.
We have used HTTP GET to query data, HTTP POST to add new data, HTTP
PUT will be used to update data when calling APIs.
To update data, we also pass a JSonObject object to the Server. The program
will convert JSonObject to Kotlin Model class, then proceed to check whether
the object exists or not, if it exists, the program will update and return true,
if not, return false. The code shown in Table 20.
Table 20.
The command line 6→8 will convert JSonObject to Kotlin Model class
Product. Command line 9 (indexOfFirst method) will check if this Product
exists or not, if it exists, it will return the found position and update the data
on line 11, then return true to the client. Otherwise, if not found, it will return
false to the client.
Similar to HTTP POST, for HTTP PUT we also go to the start function
of ProductVerticle class and we add the command:
430
Vert.X for Kotlin Restful API
router.put(“/api/products”).handler(this::updateProduct)
Run the program, and check on Postman for HTTP PUT to change the
product information.
{
“id”: 8,
“name”: “TH True Milk”,
“quantity”: 16,
431
Vert.X for Kotlin Restful API
“unitPrice”: 30.0
}
HTTP DELETE Method is used to invoke data deletion APIs. For example,
in this case we will write API to delete Product when its Id is known.
We will build an API to delete products with the following URI syntax http://
localhost:8080/api/products/{id}. So, in the start function of ProductVerticle,
we need to add the command:
router.delete(“/api/products/:id”).handler(this::deleteProduct)
Table 21.
Command line 5 will receive the id from the client, and command line
6 will return the id to a number, command line 7 will check if this product
code exists or not, if it exists, it will remove it with the remove method at
432
Vert.X for Kotlin Restful API
command line 9 and at the same time it returns true on line 10 to notify
successful deletion, otherwise it will return false when deletion fails at line 11.
Below is the detailed code of the start function in the ProductVerticle
class shown in Table 22.
Table 22.
433
Vert.X for Kotlin Restful API
To secure Restful APIs, Vert.X also supports JWT Auth provider libraries,
with many different security handling techniques, in this document we show
how to use keystore with security code as SHA256. This process includes
five main steps as follows.
434
Vert.X for Kotlin Restful API
435
Vert.X for Kotlin Restful API
Table 23.
436
Vert.X for Kotlin Restful API
Table 24.
[
“admin”,
“user1”,
“user2”,
“user3”
]
However, now we require that users who want to access the API api/users
must log in first, otherwise, they will report an Unauthorized error.
So, we will create an API /api/login (HTTP POST), the user must call this
API to login before accessing the api/users.
Then in the Step 1, we open the build.gradle file and add the Vert.X
libraries for web and Vert.X for JWT authentication, along with Google Gson.
dependencies {
implementation “org.jetbrains.kotlin:kotlin-stdlib”
implementation ‘io.vertx:vertx-web:3.9.4’
implementation ‘io.vertx:vertx-auth-jwt:3.9.4’
implementation ‘com.google.code.gson:gson:2.9.0’
}
437
Vert.X for Kotlin Restful API
In the above syntax, [secret] is the password, [jceks] is the JWT type,
keystore.jceks is the file that will be generated, with the HS256 algorithm. We
open the command and copy the keytool command above into the command
line as shown in the Figure 29, a file keystore.jceks will be created in the
computer.
By default, the keystore.jceks file will be created in the current user, which
file will we put in the project (in the project create a keys folder and copy
this file in) as shown in the Figure 30.
438
Vert.X for Kotlin Restful API
router.route(“/api/*”).handler(authHandler(jwt))
router.get(“/api/users”).handler(this::listOfUsers)
439
Vert.X for Kotlin Restful API
The api/* syntax means that every API declared behind it must authenticate.
The authHandler function is defined as follows.
The code that requires authentication when calling the full MyVerticle
API is updated in Table 25.
440
Vert.X for Kotlin Restful API
Table 25.
441
Vert.X for Kotlin Restful API
In the Step 4, we will create a Login API to get Token. In the start function
add the following two commands:
router.route(“/api*”).handler(BodyHandler.create());
router.post(“/api/login”).handler { ctx->login(ctx,jwt)}
The above code is to create the login API, which requires login (in this
case, we will use JsonObject to pass the user+password to the server). The
login function is shown in Table 26.
442
Vert.X for Kotlin Restful API
Table 26.
In Table 26, a User object in JSon format will be sent from the Client,
it is stored in the bodyAsJson property of the RoutingContext object. In
this case, we assume that the login account is admin/123 (of course, when
deploying a database such as MongoDB, we replace this with a query that
checks login data). If the login is successful, the program will return the token
in the generateToken function with a time of 60 seconds (we can adjust this
time). This token will be saved in a cookie and sent down to the Client for
processing, based on this token, when using other APIs, the user needs to
send the token to the Server to access the authorized APIs. Tabel 27 is the
detailed code of MyVerticle when adding the login API.
443
Vert.X for Kotlin Restful API
Table 27(a).
444
Vert.X for Kotlin Restful API
Table 27(b).
34
}
35
fun login(context: RoutingContext, jwtAuth: JWTAuth) {
36
try {
37
var data = context.bodyAsJson
38
var user=data.getString(“user”)
39
var pwd=data.getString(“pass”)
40
if (!(user.equals(“admin”) &&
41
pwd.equals(“123”))) {
42
return
43
}
44
val token = jwtAuth.generateToken(
45
JsonObject(),
46
JWTOptions().setExpiresInSeconds(60))
47
var cookie = Cookie.cookie(“auth”, token)
48
cookie.setHttpOnly(true)
49
.setPath(“/”).encode()
50
context.addCookie(cookie).response()
51
.putHeader(“content-type”, “text/plain”)
52
.putHeader(“Authorization”, token)
53
.end(token)
54
} catch (ex: Exception) {
55
context.response().setStatusCode(401)
56
.putHeader(“content-type”, “application/json”)
57
.end(ex.message)
58
}
59
}
60
fun listOfUsers(routingContext: RoutingContext) {
61
var users = arrayOf(“admin”,”user1”,”user2”,”user3”)
62
var gson = Gson()
63
routingContext.response()
64
.putHeader(“content-type”,
65
“application/json;charset=utf-8”)
66
.end(gson.toJson(users))
67
}
68
}
69
We proceed to run the main function in the file RunVerticle. Call the API
api/login to get token as shown in the Figure 32.
445
Vert.X for Kotlin Restful API
We have completed the chapter dealing with Restful API for Kotlin using
Vert.X, API Methods like HTTP GET, HTTP POST, HTTP PUT and HTTP
DELETE have been implemented, for each different type of method that
we use. be suitable. In addition to handling security for the API, the JWT
Authencation provider table is also implemented.
The source code of ProductRestful Project can be downloaded at
the link https://github.com/thanhtd32/kotlin/tree/main/Authentication
Restful
Readers can read more explanations of the conditional structure in the
authors’ books (Dmitry Jemerov, et al. 2017), and Programming book is
referenced (Schild, 2019), and book (Ebel, 2019), and book (Späth, 2019),
and book Vert.X (Ponge, 2020), and the book (Bailey et al., 2021).
446
Vert.X for Kotlin Restful API
EXERCISE
{”items”: [
{”type”:”CAD”,”value”:18},
{”type”:”AUD”,”value”:20},
{”type”:”EUR”,”value”:19}
]}
10. From the class model learned in question 9, please use Vert.X to build
APIs for data (GET, POST, PUT, and DELETE).
11. Use Vert.X’s JWT Authentication Provider to build a security mechanism
for the APIs in question 10.
12. Building a Complex application with Desktop and Mobile application
using Vert.X.
447
Vert.X for Kotlin Restful API
• Building Restful API using Vert.X to write all functions such as adding,
editing, viewing data, deleting data.
• Building Desktop Application:
+ Login screen: When Employee logs in successfully, it will display
the Customer operation screen corresponding to this logged-in
Employee.
Figure 34.
448
Vert.X for Kotlin Restful API
Figure 35.
449
Vert.X for Kotlin Restful API
Figure 36.
450
Vert.X for Kotlin Restful API
REFERENCES
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd
Ranch Guide (2nd ed.). Big Nerd Ranch, LLC.
Ebel, N. (2019). Mastering Kotlin: Learn advanced Kotlin programming
techniques to build apps for Android, iOS, and the web. Packt Publishing.
Jemerov & Isakova. (2017). Kotlin in Action. Manning, 320–322.
Ponge. (2020). Vert.x in Action Asynchronous and Reactive Java. Manning
Publisher.
Schild, H. (2019). Java the complete Reference (11th ed.). McGraw-Hill
Education.
Späth, P. (2019). Learn Kotlin for Android Development: The Next Generation
Language for Modern Android Apps Programming. Apress Publisher.
Tran, D. T., & Huh, J.-H. (n.d.). Full source code of the book. https://github.
com/thanhtd32/kotlin
451
452
Compilation of References
Bailey, A., Greenhalgh, D., & Skeen, J. (2021). Kotlin Programming: The Big Nerd Ranch Guide
(2nd ed.). Big Nerd Ranch, LLC.
Bailey, Greenhalgh, & Skeen. (2021), Kotlin Programming: The Big Nerd Ranch Guide (2nd
ed.). Big Nerd Ranch, LLC.
Bailey, Greenhalgh, & Skeen. (2021). Kotlin Programming: The Big Nerd Ranch Guide (2nd
ed.). Big Nerd Ranch, LLC.
Bailey, A., Greenhalgh, D., & Skeen, J. (2021). Kotlin Programming: The Big Nerd Ranch Guide
(2nd ed.). Big Nerd Ranch, LLC.
Ebel, N. (2019). Mastering Kotlin: Learn advanced Kotlin programming techniques to build
apps for Android, iOS, and the web. Packt Publishing.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Griffiths, D., & Griffiths, D. (2019). Head First Kotlin. O’Reilly Media.
Ponge. (2020). Vert.x in Action Asynchronous and Reactive Java. Manning Publisher.
Schild, H. (2019). Java the complete Reference (11th ed.). McGraw-Hill Education.
Compilation of References
Schild, H. (2019). Java the complete Reference (11th ed.). McGraw-Hill Education.
Späth, P. (2019). Learn Kotlin for Android Development: The Next Generation Language for
Modern Android Apps Programming. Apress Publisher.
Tran, D. T., & Huh, J.-H. (n.d.). Full source code of the book. https://github.com/thanhtd32/kotlin
453
454
Duy Thanh Tran recieved the President’s Award (1st prize research Ph.D.
Degree Award) at National Korea Maritime and Ocean University, Republic
of Korea in Feb., 2023. Since July 2016, he has been a Full Lecturer in the
Faculty of Information Systems, University of Economics and Law, Viet-
nam National University Ho Chi Minh City (VNU)-HCM, Vietnam. Also,
he is Associate Editor (AE) at Human-centric Computing and Information
Sciences, (HCIS), (SCIE IF=6.558). He received Best Paper Award at the
15th International Conference on Multimedia Information Technology and
Applications (MITA 2019). He is co-author of books: Basic mobile applica-
tion development (ISBN: 978-604-73-5672-0), Advanced mobile application
development (ISBN: 978-604-73-5673-7), Basic programming techniques
(ISBN: 978-604-73-7187-7), Advanced programming techniques (ISBN:
978-604-73-7493-9).
Index
C F
Checked error 101, 103 File Processing 241-242, 255, 267, 275
Class Inheritance 212 For – Closed Range 76, 91-92
Collections 159-161, 164, 398 For – DownTo Navigation 79, 91-92
Comments 1, 25, 27, 29 For – Half-Open Range 77, 91-92
Commonly Important Libraries 116 For – Set Object Loop 81
CompareTo 43, 138 For – Step Navigation 78, 91-92
Comparison Operators 39, 42, 51 Function Summary 132
Conditional Execution 53
Conditional Statement 59, 375 G
Contains 131, 134, 136, 157, 239, 261, 276,
336, 348, 358, 368, 437 Graphic User Interface (GUI) 306-308,
Continue Statement 75-76, 90 311, 322, 331, 340-341, 345-347, 354
Conversion 31-32, 35-38, 50, 129 Group Multiple Conditions 53-54, 65-66
D H
Data Classes 205, 211 Hello World Project 15
Data Types 31-32, 34-35, 38, 50, 159, 198, Hierarchical Collection 160
257, 375, 396
Date Processing Library 116-118
Debug 104, 106-108, 111-112
Index
N T
Nested Classes 205, 207, 211 Text File 241-242, 244-249, 252, 254-255,
Nested Conditionals 53-54, 58 273, 275, 301-302, 390
Numeric Data Processing Library 116-117 This Reference 195, 197
Throw Exception Keyword 103, 112
O Trim 131, 136-137
Try Catch Handler 102, 112
Object-Oriented Programming (OOP) 140, Two-Dimensional Array Processing 152,
169-170, 179, 193, 196-197 154
One-Dimensional Array Processing 148
456
Index
U W
Unary Operators 31-32, 39, 50 When Expression 60, 63, 65-66, 68
Unchecked error 101 While Loop Execution 83, 86
Uppercase 73, 138, 140-141, 180
User Input 47, 158 X
V XML File 19, 241, 267-269, 272, 274-275,
290, 301-303, 390
Variables 31-33, 35, 38, 46, 50, 107-110,
180, 195-197, 207-208, 223
Vert.X 394, 399-403, 405-408, 414, 420,
423, 425, 430, 432, 434, 437, 446-
448, 451
457