0% found this document useful (0 votes)
15 views

Kotlin

Kotlin is a modern programming language that is compatible with Java. It can be used for mobile, web, and server-side applications. Kotlin code is concise and safe, and the language is easy to learn especially for Java developers.

Uploaded by

mzahidrasool50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Kotlin

Kotlin is a modern programming language that is compatible with Java. It can be used for mobile, web, and server-side applications. Kotlin code is concise and safe, and the language is easy to learn especially for Java developers.

Uploaded by

mzahidrasool50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Kotlin Introduction

What is Kotlin?
Kotlin is a modern, trending programming language that was released in
2016 by JetBrains.

It has become very popular since it is compatible with Java (one of the most
popular programming languages out there), which means that Java code
(and libraries) can be used in Kotlin programs.

Kotlin is used for:

 Mobile applications (specially Android apps)


 Web development
 Server side applications
 Data science
 And much, much more!

Why Use Kotlin?


 Kotlin is fully compatible with Java
 Kotlin works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc.)
 Kotlin is concise and safe
 Kotlin is easy to learn, especially if you already know Java
 Kotlin is free to use
 Big community/support

Kotlin IDE
The easiest way to get started with Kotlin, is to use an IDE.

An IDE (Integrated Development Environment) is used to edit and compile


code.

We will use IntelliJ (developed by the same people that created Kotlin) which
is free to download from https://www.jetbrains.com/idea/download/.
Kotlin Syntax
Example

fun main() {

println("Hello World")

Example explained
The fun keyword is used to declare a function. A function is a block of code
designed to perform a particular task. In the example above, it declares
the main() function.

The main() function is something you will see in every Kotlin program. This
function is used to execute code. Any code inside the main() function's curly
brackets {} will be executed.

For example, the println() function is inside the main() function, meaning
that this will be executed. The println() function is used to output/print
text, and in our example it will output "Hello World".

Good To Know: In Kotlin, code statements do not have to end with a


semicolon (;) (which is often required for other programming languages,
such as Java, C++, C#, etc.).

Kotlin Output (Print Text)


Kotlin Output (Print)
The println() function is used to output values/print text:
Example

fun main() {

println("Hello World")

}
You can add as many println() functions as you want. Note that it will add
a new line for each function:

Example

fun main() {

println("Hello World!")

println("I am learning Kotlin.")

println("It is awesome!")

You can also print numbers, and perform mathematical calculations:

Example

fun main() {

println(3 + 3)

The print() function


There is also a print() function, which is similar to println(). The only
difference is that it does not insert a new line at the end of the output:

Example

fun main() {

print("Hello World! ")

print("I am learning Kotlin. ")

print("It is awesome!")

Note that we have added a space character to create a space between the
sentences.
Kotlin Comments
Kotlin Comments
Comments can be used to explain Kotlin code, and to make it more readable.
It can also be used to prevent execution when testing alternative code.

Single-line Comments
Single-line comments starts with two forward slashes (//).

Any text between // and the end of the line is ignored by Kotlin (will not be
executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment

println("Hello World")

This example uses a single-line comment at the end of a line of code:

Example

println("Hello World") // This is a comment

Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Kotlin.

This example uses a multi-line comment (a comment block) to explain the


code:

/* The code below will print the words Hello World

to the screen, and it is amazing */

println("Hello World")
Kotlin Variables
Kotlin Variables
Variables are containers for storing data values.

To create a variable, use var or val, and assign a value to it with the equal
sign (=):

Syntax

var variableName = value

val variableName = value

Example

var name = "John"

val birthyear = 1975

println(name) // Print the value of name

println(birthyear) // Print the value of birthyear

The difference between var and val is that variables declared with
the var keyword can be changed/modified, while val variables cannot.

Variable Type
Unlike many other programming languages, variables in Kotlin do not need
to be declared with a specified type (like "String" for text or "Int" for
numbers, if you are familiar with those).

To create a variable in Kotlin that should store text and another that should
store a number, look at the following example:

Example

var name = "John" // String (text)

val birthyear = 1975 // Int (number)


println(name) // Print the value of name

println(birthyear) // Print the value of birthyear

Kotlin is smart enough to understand that "John" is a String (text), and


that 1975 is an Int (number) variable.

However, it is possible to specify the type if you insist:

Example

var name: String = "John" // String

val birthyear: Int = 1975 // Int

println(name)

println(birthyear)

You can also declare a variable without assigning the value, and assign the
value later. However, this is only possible when you specify the type:

Example

This works fine:

var name: String

name = "John"

println(name)

Example

This will generate an error:

var name

name = "John"

println(name)

Notes on val
When you create a variable with the val keyword, the value cannot be
changed/reassigned.
The following example will generate an error:

Example

val name = "John"

name = "Robert" // Error (Val cannot be reassigned)

println(name)

When using var, you can change the value whenever you want:

Example

var name = "John"

name = "Robert"

println(name)

So When To Use val?

The val keyword is useful when you want a variable to always store the
same value, like PI (3.14159...):

Example

val pi = 3.14159265359

println(pi)

Display Variables
Like you have seen with the examples above, the println() method is often
used to display variables.

To combine both text and a variable, use the + character:

Example

val name = "John"

println("Hello " + name)

You can also use the + character to add a variable to another variable:

Example

val firstName = "John "


val lastName = "Doe"

val fullName = firstName + lastName

println(fullName)

For numeric values, the + character works as a mathematical operator:

Example

val x = 5

val y = 6

println(x + y) // Print the value of x + y

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 Then we use the println() method to display the value of x + y,
which is 11

Variable Names
A variable can have a short name (like x and y) or more descriptive names
(age, sum, totalVolume).

The general rule for Kotlin variables are:

 Names can contain letters, digits, underscores, and dollar signs


 Names should start with a letter
 Names can also begin with $ and _
 Names are case sensitive ("myVar" and "myvar" are different
variables)
 Names should start with a lowercase letter and it cannot contain
whitespace
 Reserved words (like Kotlin keywords, such as var or String) cannot
be used as names

camelCase variables
You might notice that we used firstName and lastName as variable names
in the example above, instead of firstname and lastname. This is called
"camelCase", and it is considered as good practice as it makes it easier to
read when you have a variable name with different words in it, for example
"myFavoriteFood", "rateActionMovies" etc.
Kotlin Data Types
Kotlin Data Types
In Kotlin, the type of a variable is decided by its value:

Example

val myNum = 5 // Int

val myDoubleNum = 5.99 // Double

val myLetter = 'D' // Char

val myBoolean = true // Boolean

val myText = "Hello" // String

However, you learned from the previous chapter that it is possible to specify
the type if you want:

Example

val myNum: Int = 5 // Int

val myDoubleNum: Double = 5.99 // Double

val myLetter: Char = 'D' // Char

val myBoolean: Boolean = true // Boolean

val myText: String = "Hello" // String

Sometimes you have to specify the type, and often you don't. Anyhow, it is
good to know what the different types represent.

You will learn more about when you need to specify the type later.

Data types are divided into different groups:

 Numbers
 Characters
 Booleans
 Strings
 Arrays
Numbers
Number types are divided into two groups:

Integer types store whole numbers, positive or negative (such as 123 or -


456), without decimals. Valid types are Byte, Short, Int and Long.

Floating point types represent numbers with a fractional part, containing


one or more decimals. There are two types: Float and Double.

If you don't specify the type for a numeric variable, it is most often returned
as Int for whole numbers and Double for floating point numbers.

Integer Types
Byte
The Byte data type can store whole numbers from -128 to 127. This can be
used instead of Int or other integer types to save memory when you are
certain that the value will be within -128 and 127:

Example

val myNum: Byte = 100

println(myNum)

Short
The Short data type can store whole numbers from -32768 to 32767:

Example

val myNum: Short = 5000

println(myNum)

Int
The Int data type can store whole numbers from -2147483648 to
2147483647:
Example

val myNum: Int = 100000

println(myNum)

Long
The Long data type can store whole numbers from -9223372036854775807
to 9223372036854775807. This is used when Int is not large enough to
store the value. Optionally, you can end the value with an "L":

Example

val myNum: Long = 15000000000L

println(myNum)

Difference Between Int and Long


A whole number is an Int as long as it is up to 2147483647. If it goes
beyond that, it is defined as Long:

Example

val myNum1 = 2147483647 // Int

val myNum2 = 2147483648 // Long

Floating Point Types


Floating point types represent numbers with a decimal, such as 9.99 or
3.14515.

The Float and Double data types can store fractional numbers:

Float Example

val myNum: Float = 5.75F

println(myNum)

Double Example

val myNum: Double = 19.99


println(myNum)

Use Float or Double?


The precision of a floating point value indicates how many digits the value
can have after the decimal point. The precision of Float is only six or seven
decimal digits, while Double variables have a precision of about 15 digits.
Therefore it is safer to use Double for most calculations.

Also note that you should end the value of a Float type with an "F".

Booleans
The Boolean data type and can only take the values true or false:

Example

val isKotlinFun: Boolean = true

val isFishTasty: Boolean = false

println(isKotlinFun) // Outputs true

println(isFishTasty) // Outputs false

Boolean values are mostly used for conditional testing.

Characters
The Char data type is used to store a single character. A char value must be
surrounded by single quotes, like 'A' or 'c':

Example

val myGrade: Char = 'B'

println(myGrade)

Unlike Java, you cannot use ASCII values to display certain characters. The
value 66 would output a "B" in Java, but will generate an error in Kotlin:

Example

val myLetter: Char = 66

println(myLetter) // Error
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:

Example

val myText: String = "Hello World"

println(myText)

Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.

Type Conversion
Type conversion is when you convert the value of one data type to another
type.

In Kotlin, numeric type conversion is different from Java. For example, it is


not possible to convert an Int type to a Long type with the following code:

Example

val x: Int = 5

val y: Long = x

println(y) // Error: Type mismatch

To convert a numeric data type to another type, you must use one of the
following
functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble() o
r toChar():

Example

val x: Int = 5

val y: Long = x.toLong()

println(y)
Kotlin Input
Kotlin standard input is the basic operation performed to flow byte streams
from input device such as Keyboard to the main memory of the system.
You can take input from user with the help of the following function:
readline() method
Scanner class

Take input from user using readline()


method
fun main() {
print("Enter text: ")
var input = readLine()
print("You entered: $input")
}

Output:
Enter text: Hello, Geeks! You are learning how to take input using
readline()
You entered: Hello, Geeks! You are learning how to take input using
readline()

Take input from user using Scanner class –


If you are taking input from user other than String data type, you need to use
Scanner class. To use Scanner first of all you have to import the Scanner on
the top of the program.
import java.util.Scanner;
Create an object for the scanner class and use it to take input from the user.
In the below program we will show you how to take input of integer, float and
boolean data type.
import java.util.Scanner

fun main() {

// create an object for scanner class


val number1 = Scanner(System.`in`)
print("Enter an integer: ")
// nextInt() method is used to take
// next integer value and store in enteredNumber1 variable
var enteredNumber1:Int = number1.nextInt()
println("You entered: $enteredNumber1")

val number2 = Scanner(System.`in`)


print("Enter a float value: ")

// nextFloat() method is used to take next


// Float value and store in enteredNumber2 variable
var enteredNumber2:Float = number2.nextFloat()
println("You entered: $enteredNumber2")

val booleanValue = Scanner(System.`in`)


print("Enter a boolean: ")
// nextBoolean() method is used to take
// next boolean value and store in enteredBoolean variable
var enteredBoolean:Boolean = booleanValue.nextBoolean()
println("You entered: $enteredBoolean")
}

Output
Enter an integer: 123
You entered: 123
Enter a float value: 40.45
You entered: 40.45
Enter a boolean: true
You entered: true

Take input from user without using the


Scanner class
Here, we will use readline() to take input from the user and no need to import
Scanner class.
readline()!! take the input as a string and followed by (!!) to ensure that the
input value is not null.
fun main() {

print("Enter an Integer value: ")


val string1 = readLine()!!

// .toInt() function converts the string into Integer


var integerValue: Int = string1.toInt()
println("You entered: $integerValue")

print("Enter a double value: ")


val string2= readLine()!!

// .toDouble() function converts the string into Double


var doubleValue: Double = string2.toDouble()
println("You entered: $doubleValue")
}

Output:
Enter an Integer value: 123
You entered: 123
Enter a double value: 22.22222
You entered: 22.22222

Kotlin Operators
Kotlin Operators
Operators are used to perform operations on variables and values.

The value is called an operand, while the operation (to be performed


between the two operands) is defined by an operator:

Operand Operator Operand

100 + 50

In the example below, the numbers 100 and 50 are operands, and
the + sign is an operator:

Example

var x = 100 + 50

Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or
a variable and a variable:
Example

var sum1 = 100 + 50 // 150 (100 + 50)

var sum2 = sum1 + 250 // 400 (150 + 250)


var
sum
3 =
Operator Name Description Example sum
2 +
sum
2
//
800
(40
0 +
400
)

Kotl
in
divi
des
the
ope
rat
ors
into
the
foll
owi
ng
gro
ups
:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
+ Addition Adds together two values x+y

- Subtraction Subtracts one value from x-y


another

* Multiplication Multiplies two values x*y

/ Division Divides one value from another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value by 1 ++x

-- Decrement Decreases the value by 1 --x

Kotlin Assignment Operators


Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

Example

var x = 10
The addition assignment operator (+=) adds a value to a variable:

Example

var x = 10
x += 5

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

Kotlin Comparison Operators


Comparison operators are used to compare two values, and returns
a Boolean value: either true or false.

Operator Name Example


== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Kotlin Logical Operators


Logical operators are used to determine the logic between variables or values:

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false

if the result is true

Kotlin Strings
Strings are used for storing text.

A string contains a collection of characters surrounded by double quotes:

Example

var greeting = "Hello"

Unlike Java, you do not have to specify that the variable should be a String.
Kotlin is smart enough to understand that the greeting variable in the
example above is a String because of the double quotes.

However, just like with other data types, you can specify the type if you
insist:

Example

var greeting: String = "Hello"

Note: If you want to create a String without assigning the value (and assign
the value later), you must specify the type while declaring the variable:

Example
This works fine:

var name: String


name = "John"

println(name)

Example
This will generate an error:

var name

name = "John"

println(name)

String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:

Example

var firstName = "John"

var lastName = "Doe"

println(firstName + " " + lastName)

Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.

String Templates/Interpolation
Instead of concatenation, you can also use "string templates", which is an
easy way to add variables and expressions inside a string.

Just refer to the variable with the $ symbol:

Example

var firstName = "John"

var lastName = "Doe"

println("My name is $firstName $lastName")


String Templates" is a popular feature of Kotlin, as it reduces the amount of
code. For example, you do not have to specify a whitespace between
firstName and lastName, like we did in the concatenation example."

Kotlin Booleans
Very often, in programming, you will need a data type that can only have
one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, Kotlin has a Boolean data type, which can take the
values true or false.

Boolean Values
A boolean type can be declared with the Boolean keyword and can only take
the values true or false:

Example

val isKotlinFun: Boolean = true

val isFishTasty: Boolean = false

println(isKotlinFun) // Outputs true

println(isFishTasty) // Outputs false

Just like you have learned with other data types, the example above can also
be written without specifying the type, as Kotlin is smart enough to
understand that the variables are Booleans:

Example

val isKotlinFun = true

val isFishTasty = false

println(isKotlinFun) // Outputs true

println(isFishTasty) // Outputs false


Boolean Expression
A Boolean expression returns a Boolean value: true or false.

You can use a comparison operator, such as the greater than (>) operator
to find out if an expression (or a variable) is true:

Example

val x = 10

val y = 9
println(x > y) // Returns true, because 10 is greater than 9

Example

println(10 > 9) // Returns true, because 10 is greater than 9

In the examples below, we use the equal to (==) operator to evaluate an


expression:

Example

val x = 10;

println(x == 10); // Returns true, because the value of x is equal to


10

Example

println(10 == 15); // Returns false, because 10 is not equal to 15

The Boolean value of an expression is the basis for all Kotlin comparisons and
conditions.

Kotlin If ... Else


Kotlin supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different
decisions.

Kotlin has the following conditionals:

 Use if to specify a block of code to be executed, if a specified


condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use when to specify many alternative blocks of code to be executed

Note: Unlike Java, if..else can be used as a statement or as


an expression (to assign a value to a variable) in Kotlin. See an example at
the bottom of the page to better understand it.

Kotlin if
Use if to specify a block of code to be executed if a condition is true.

Syntax

if (condition) {

// block of code to be executed if the condition is true

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate
an error.

In the example below, we test two values to find out if 20 is greater than 18.
If the condition is true, print some text:

Example

if (20 > 18) {

println("20 is greater than 18")

We can also test variables:


Example

val x = 20

val y = 18

if (x > y) {

println("x is greater than y")

Example explained

In the example above we use two variables, x and y, to test whether x is


greater than y (using the > operator). As x is 20, and y is 18, and we know
that 20 is greater than 18, we print to the screen that "x is greater than y".

Kotlin else
Use else to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example

val time = 20

if (time < 18) {

println("Good day.")

} else {

println("Good evening.")

}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition
is false, so we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

Kotlin else if
Use else if to specify a new condition if the first condition is false.

Syntax

if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and


condition2 is true

} else {

// block of code to be executed if the condition1 is false and


condition2 is false

Example

val time = 22

if (time < 10) {

println("Good morning.")

} else if (time < 20) {

println("Good day.")

} else {

println("Good evening.")

}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Kotlin If..Else Expressions


In Kotlin, you can also use if..else statements as expressions (assign a
value to a variable and return it):

Example

val time = 20

val greeting = if (time < 18) {

"Good day."

} else {

"Good evening."

println(greeting)

When using if as an expression, you must also include else (required).

Note: You can ommit the curly braces {} when if has only one statement:

Example

fun main() {

val time = 20

val greeting = if (time < 18) "Good day." else "Good evening."

println(greeting)

}
Tip: This example is similar to the "ternary operator" (short hand if...else) in
Java.

Kotlin when
Instead of writing many if..else expressions, you can use
the when expression, which is much easier to read.

It is used to select one of many code blocks to be executed:

Example
Use the weekday number to calculate the weekday name:

val day = 4

val result = when (day) {

1 -> "Monday"

2 -> "Tuesday"

3 -> "Wednesday"

4 -> "Thursday"

5 -> "Friday"

6 -> "Saturday"

7 -> "Sunday"

else -> "Invalid day."

println(result)

// Outputs "Thursday" (day 4)

The when expression is similar to the switch statement in Java.

This is how it works:

 The when variable (day) is evaluated once


 The value of the day variable is compared with the values of each
"branch"
 Each branch starts with a value, followed by an arrow (->) and a result
 If there is a match, the associated block of code is executed
 else is used to specify some code to run if there is no match
 In the example above, the value of day is 4, meaning "Thursday" will
be printed

Note: When using when as an expression, you must also


include else (required). But you can ommit else while using when in
statement.

You might also like