Book Image

Hands-On Object-Oriented Programming with Kotlin

By : Abid Khan, Igor Kucherenko
Book Image

Hands-On Object-Oriented Programming with Kotlin

By: Abid Khan, Igor Kucherenko

Overview of this book

Kotlin is an object-oriented programming language. The book is based on the latest version of Kotlin. The book provides you with a thorough understanding of programming concepts, object-oriented programming techniques, and design patterns. It includes numerous examples, explanation of concepts and keynotes. Where possible, examples and programming exercises are included. The main purpose of the book is to provide a comprehensive coverage of Kotlin features such as classes, data classes, and inheritance. It also provides a good understanding of design pattern and how Kotlin syntax works with object-oriented techniques. You will also gain familiarity with syntax in this book by writing labeled for loop and when as an expression. An introduction to the advanced concepts such as sealed classes and package level functions and coroutines is provided and we will also learn how these concepts can make the software development easy. Supported libraries for serialization, regular expression and testing are also covered in this book. By the end of the book, you would have learnt building robust and maintainable software with object oriented design patterns in Kotlin.
Table of Contents (14 chapters)

Data types in Kotlin

In the same way as any other modern language, Kotlin uses variables or data types, which are among the most important features in programming. These variables are created to handle different types of data, including numbers, letters, words, and so on. Variables are allocated locations in memory for storing all kinds of data.

The data types in Kotlin are as follows:

  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double
  • Character
  • Boolean

Declaring a variable in Kotlin

There are two keywords available in Kotlin—var and val. The var keyword declares a mutable data type and the val keyword declares an immutable or read-only variable.

The var keyword

The var keyword declares a mutable property or local variable. This means that the variable can be changed or updated as follows during the course of the entire program:

var age = 25

In the preceding code, var is a keyword, age is a variable name, and 25 is an assigned integer value. Let's see some other variable definitions to understand the declarations better:

  • var myChar = 'A': myChar is a single character variable
  • var name = "Bob": A name is a string type variable
  • var age = 10: age is an integer type variable
  • var height = 5.10: height is a double type variable

In Kotlin, a variable must have a value assigned. Without proper initialization, it does not allow variable declarations:

var age //In-Valid Declaration; compiler error
var age = 25
Valid Declaration

The value of the variable can be changed, but the variable type itself cannot be changed. If we try to re-assign an integer variable with double or string, the compiler will throw the mismatch error type:

var age = 10 // Data type integer - Valid declaration
age = 10.2 // Invalid assignment - not an integer compiler error
age = "hello" // Invalid assignment not an integer - compiler error

It is necessary that we declare different variables with the var keyword, as demonstrated here:

fun main(args: Array<String>) {
var student = "Bob" // String variable
var age = 25 // Integer variable
var height = 5.6 // Double variable
println("Name is $student age is $age and height is $height")
}

The val keyword

The val keyword is a read-only variable that is used to declare an immutable variable. Immutable means that once the variable is assigned, it will remain the same until the end of the application's life:

val age = 25 

In the preceding code line, val is a keyword, age is a variable name, and 25 is an integer value assigned.

val is the same as var; the variable type is dependent on the value assigned to the variable.

The read-only feature is actually one of the safety features provided by Kotlin.

Once the variable is declared, it is not possible to update it under any circumstances. This feature becomes more important when we are writing a complex application or a program of scientific calculations:

val pi = 3.14159

Knowing that the value of pi is constant, it would be a good practice to use val instead of var to make sure that the value remains constant and cannot be changed accidentally. Once declared as val, try to re-assign any other value to pi as follows:

pi = 123.345 // The result: Compiler will throw an error: "val cannot re-assign".

It is necessary that we declare different variables with the val keyword:

fun main(args: Array<String>) {
val name = "Herry" // String variable
val PI = 3.1415 // Double variable
val programmingLanguage = "Kotlin"
programmingLanguage = "Java" // Error: val cannot be reassigned
println("Name is $name and my favorite programming language is $programmingLanguage")
}

Type inference

Type inference is a mechanism in which the Kotlin compiler plays its role to find out a variable type. Kotlin will determine the data type by understanding the value assigned. It intelligently infers the type by the value and then makes the variable of the data type respectively. This technique is called type inference. In all the previous code, whether a data type is declared with val or var are examples of type inference:

val age = 25
val name = "Bob"

In the preceding code, age is an integer and name is a string type variable. The type of these variables is inferred by the compiler.

Type annotation

In Kotlin, we can also declare a specific type of variable with var variableName : nameOfDataType type annotation:

var myInteger : Int
var myString : String
val myDouble : Double

Once the variables are declared, we can assign values to them:

myInteger = 10
myString = "Hello"
myDouble = 12.123

Having variable declarations with explicit data types and assigning a value at the same time is also possible:

val myInt : Int = 10
var myString : String = "Hello"

Variable declaration and initialization is explained in the following example:

fun main(args: Array<String>) {
var myName: String // Variables can be initialized explicitly
myName = "Jon" // Initialization
// declaration and initialization in one line
var myInt: Int = 10
var myLong: Long = 11
var myShort: Short = 11
var myByte: Byte = -128
var d1 = 5.10 // Declaration of Double and Float
var d2: Double = 5.10
var f1 = 5.10
var f2: Float = 5.10f
}

Kotlin data types are divided into the following groups:

  • Number data types
  • Real data types
  • Boolean data types
  • Character data types

Now let's have a look at each category in the following sections.

Number data types

Number data types accept whole numbers and do not support fractions. Kotlin provides four different types of number variables—Integer, Long, Byte, and Short. These data types can be declared with and without type annotation. It can also be easily declared with the following syntax:

var myInt : Int =10  // For Integer variable
var myInt = 10
var myLong : Long = 11 // For Long Variable
var myShort : Short = 11 // For Short Variable
var myByte : Byte = -100 For byte variable

MAX_VALUE and MIN_VALUE can be used to find the capacity of each variable.

See the following example:

fun main(args: Array<String>) {
println("max integer " + Integer.MAX_VALUE)
println("min integer " + Integer.MIN_VALUE)
}

The following output shows the maximum and minimum value an integer can hold:

Real data types

In this category, Kotlin provides two data types:

  • Float
  • Double

These data types can store values containing decimal places. Float and Double are the floating point data types that are used to store real number values. A Float can contain 4 bytes of information, while the Double data type can handle 8 bytes. Kotlin allows us to handle scientific notation with the Double data type as follows:

  1. Create two Double types of variables as follows:
  • Create d1 with an explicit declaration of the data type
  • Create d2 with an implicit declaration:
fun main(args: Array<String>) {
var d1 : Double = 7.20E15 // Scientific calculation
var d2 = 7.20e-15
  1. Assign scientific values to both variables and print:
println("Value of d1 = " + d1 + " and Value of d2 = " + d2)
}

The Value of d1 = 7.02E15 and Value of d2 = 7.02E-15 printed values are the same, except the value of d2 is capitalized.

Boolean data type

Boolean is a data type that contains one of two values—true or false. Because of its nature, the Boolean variable requires only one single bit for storing data. This bit can be on or off, true or false, 0 or 1. Let's declare some Boolean variables for further discussion:

var result : Boolean = true
var isEmpty : Boolean = false

In the same way as other variables, the Boolean variable can be declared without type inference:

var value = false
var result = true

Basically, this data type is used for comparing two values, getting results by setting a Boolean as a checkpoint to verify the results via comparison, and getting an answer by way of true or false. Let's see an example of how this can happen:

fun main(args: Array<String>) {

var result : Boolean // Boolean variable
var num1 = 20
var num2 = 10

result = num1 >= num2
println("$num1 is greater than $num2 = $result")

result = num1 < num2
println("$num1 is greater than $num2 = $result")
}

In this example, we have two integer variables named num1 and num2, as well as a Boolean variable named result. If num1 is greater than or equal to num2, true will be assigned to result; otherwise, false will be assigned.

Character data type

The character data type is one of the data types available in Kotlin. This can contain 2 bytes of information and it can also store pretty much all the characters that you see on your keyboard. The syntax is the same as any other declaration—the word Char is used to declare a character variable and the value on the right-hand side must be enclosed by single quotes:

var mychar : Char = 'A'

Let's take a look at some examples. When character values are assigned to the Char data type, this can be displayed as follows:

var charA : Char = 'A'
var charZ : Char = 'Z'
var char1 = '1'
var char0 = '0'

Each character has a unique Unicode for its representation, and the character data type can be stored in Unicode values. Let's display A, Z, 1, and 0 by using a Unicode character. The syntax for storing the Unicode is pretty much the same, except \u is required at the beginning of the code. This is demonstrated as follows:

var ucharA : Char = '\u0041'
var ucharZ : Char = '\u005A'
var uchar1 = '\u0031'
var uchar0 = '\u0030'

The following code shows how a character data type handles different characters:

fun main(args: Array<String>) {
var charA : Char = 'A'
var charZ : Char = 'Z'
var char1 = '1'
var char0 = '0'
println("$charA $charZ $char1 $char0")

// Unicode Character
var ucharA : Char = '\u0041'
var ucharZ : Char = '\u005A'
var uchar1 = '\u0031'
var uchar0 = '\u0030'
println("$ucharA $ucharZ $uchar1 $uchar0")
}

Type checking with the is keyword

Type inference is one of the most powerful features in Kotlin, but sometimes it becomes hazardous when the type of variable is unknown. For example, we are asked to write a function that can take variable of the Any type. This can be float, string, or int:

fun func(x: Any) { 
// What is the type of x
}

To handle this tricky situation, Kotlin provides an is keyword to verify the variable type. The syntax for this is as follows:

x is Int
x is Char

This check will return true if x is an integer or character; otherwise, it will return false. Check the following examples:

fun func(x: Any) { 
if(x is Float){
println("x is Float")
} else if(x is String){
println("x is String")
}

!is can be used to verify whether or not a variable is a required type:

fun func(x: Any) { 
if(x !is Float){
println("f is not Float")
}
}

String variable

A string is a well-structured set of characters, words, sentences, and paragraphs. String is a widely used data type in Kotlin. Unlike other variables, such as Integer, Float, or Boolean, which contain one specific type of value, Strings can contain a collection of different values and can store pretty much everything and anything.

Like other Kotlin data types, String variables can be declared with or without type inference, and everything within double quotes will be considered as a string:

var variable_name : String = "value in double quotes"
var message : String = "Hello"
var question : String = "What is your name?"

A string variable, message, is initialized with Hello, and another string variable, question, is assigned with What is your name?. A string variable can be declared with the var or val keyword without stating the variable type, for example, val name = "Bob":

fun main(args: Array<String>) {
var message : String = "Hello"
var question : String = "What is your name?"
println(question)
val name = "Bob"
var address = "Stockholm, Sweden"
println("My name is $name and i live in $address")
}