Android Chapter-1
Android Chapter-1
SURENDRANAGAR
Basics of Kotlin
Kotlin is a cross-platform programming language that may be used as an
alternative to Java for Android App Development.
Kotlin Jobs
Kotlin is very high in demand and all major companies are moving
towards Kotlin to develop their web and mobile applications.
Following are the great companies who are using Kotlin:
Google
Amazon
Netflix
1|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Pinterest
Uber
Trello
Coursera
Basecamp
Corda
JetBrains and many more
Kotlin Variable
Variable refers to a memory location. It is used to store data. The data of
variable can be changed and reused depending on condition or on
information passed to the program.
Variable Declaration
Kotlin variable is declared using keyword var and val.
2|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
o Number
o Character
o Boolean
o Array
o String
Kotlin Output :-
Output
Hello World!
Welcome to kotlin
The methods print() and println() are internally call System.out.print() and
System.out.println() respectively.
3|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Kotlin Input :-
Kotlin has standard library function readLine() which is used for reads line of
string input from standard input stream. It returns the line read or null.
Output:
While using the readLine() function, input lines other than String are explicitly
converted into their corresponding types.
Operators
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Kotlin is rich in built-in operators
and provide the following types of operators:
4|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Arithmetic Operators
Relational Operators
Assignment Operators
Unary Operators
Logical Operators
Bitwise Operations
5|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Example:-
fun main(args: Array<String>) {
val x: Int = 40
val y: Int = 20
6|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
== is equal to x == y
!= not equal to x != y
Example:-
fun main(args: Array<String>) {
val x: Int = 40
val y: Int = 20
7|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
println("x = " + x)
println("y = " + y)
}
output:
x = 40
y = 20
operators:-
= x = 10 x = 10
+= x += 10 x = x - 10
-= x -= 10 x = x - 10
*= x *= 10 x = x * 10
8|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
/= x /= 10 x = x / 10
%= x %= 10 x = x % 10
Example:-
x += 5
println("x += 5 = " + x )
x = 40;
x -= 5
println("x -= 5 = " + x)
x = 40
x *= 5
println("x *= 5 = " + x)
x = 40
x /= 5
println("x /= 5 = " + x)
x = 43
x %= 5
println("x %= 5 = " + x)
}
9|Page
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
output:-
x += 5 = 45
x -= 5 = 35
x *= 5 = 200
x /= 5 = 8
x %= 5 = 3
+ unary plus +x
- unary minus -x
++ increment by 1 ++x
-- decrement by 1 --x
Example:-
fun main(args: Array<String>) {
var x: Int = 40
var b:Boolean = true
10 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Kotlin logical operators are used to determine the logic between two
variables or values:
Following is the list of Kotlin Logical Operators:
11 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Example:-
fun main(args: Array<String>) {
var x: Boolean = true
var y:Boolean = false
12 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Example
fun main(args: Array<String>) {
var x:Int = 60 // 60 = 0011 1100
var y:Int = 13 // 13 = 0000 1101
var z:Int
13 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
println("x.or(y) = " + z)
Decision Making
In Kotlin, if is an expression is which returns a value. It is used for control
the flow of program structure. There is various type of if expression in
Kotlin.
o if-else expression
o if-else if-else ladder expression
o nested if expression
Syntax:-
14 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
if (condition) {
// code block A to be executed if condition is true
} else {
// code block B to be executed if condition is false
}
Example
You can try the following example:
fun main(args: Array<String>) {
val age:Int = 10
15 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
16 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
}
Example
fun main(args: Array<String>) {
val age:Int = 13
} else {
// code block D to be executed if condition1 is false
}
Example
fun main(args: Array<String>) {
val age:Int = 20
18 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Kotlin supports various types of loops and in this chapter we are going to
learn Kotlin for loop.
Kotlin For Loop
Kotlin for loop iterates through anything that provides an iterator ie. that
contains a countable number of values, for example arrays, ranges, maps
or any other collection available in Kotlin. Kotlin for loop is equivalent to
the foreach loop in languages like C#.
Syntax:-
for (item in collection)
{
// body of loop
}
Iterate Through a Range
fun main(args: Array<String>) {
for (item in 1..5) {
println(item)
}
}
output:
1
2
3
4
5
Let's see one more example where the loop will iterate through another range,
but this time it will step down instead of stepping up as in the above example:
19 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Syntax
The syntax of the Kotlin while loop is as follows:
while (condition) {
When Kotlin program reaches the while loop, it checks the given condition, if
given condition is true then body of the loop gets executed, otherwise program
starts executing code available after the body of the while loop .
Example
Following is an example where the while loop continue executing the body of
the loop as long as the counter variable i is greater than 0:
var i = 5;
20 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
while (i > 0) {
println(i)
i--
output:
The loop will always be executed at least once, even if the condition is false,
because the code block is executed before the condition is tested.
Syntax
The syntax of the Kotlin do...while loop is as follows:
do{
}while( condition )
When Kotlin program reaches the do...while loop, it directly enters the body of
the loop and executes the available code before it checks for the given
21 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
condition. If it finds given condition is true, then it repeats the execution of the
loop body and continue as long as the given condition is true.
Example
Following is an example where the do...while loop continue executing the body
of the loop as long as the counter variable i is greater than 0:
var i = 5;
do{
println(i)
i--
}while(i > 0)
When you run the above Kotlin program, it will generate the following output:
22 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Functions
A function is a block of code which is written to perform a particular task.
Functions are supported by all the modern programming languages and
they are also known as methods or subroutines.
At a broad level, a function takes some input which is called parameters,
perform certain actions on these inputs and finally returns a value.
Kotlin Built-in Functions
Kotlin provides a number of built-in functions, we have used a number of
buil-in functions in our examples. For example print() and println() are
the most commonly used built-in function which we use to print an
output to the screen.
Example
fun main(args: Array<String>) {
println("Hello, World!")
}
User-Defined Functions
Kotlin allows us to create our own function using the keyword fun. A user
defined function takes one or more parameters, perform an action and
return the result of that action as a value.
Syntax:-
fun functionName(){
// body of function
}
Once we defined a function, we can call it any number of times whenever
it is needed. Following isa simple syntax to call a Kotlin function:
functionName()
Example:-
Following is an example to define and call a user-defined function which
will print simple "Hello, World!":
23 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
24 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Return Values
A kotlin function return a value based on requirement. Again it is very
much optional to return a value.
To return a value, use the return keyword, and specify the return type
after the function's parantheses
Example:-
Following is an example to write a user-defined function which will add
two given numbers and return the sum:
fun main(args: Array<String>)
{
val a = 10
val b = 20
return x
}
output:
30
Unit-returning Functions
If a function does not return a useful value, its return type is Unit. Unit is
a type with only one value which is Unit.
25 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
println( x )
}
The Unit return type declaration is also optional. The above code is equivalent
to:
fun sumTwo(a:Int, b:Int)
{
val x = a + b
println( x )
}
Kotlin Recursive Function
Recursion functions are useful in many scenerios like calculating factorial
of a number or generating fibonacci series. Kotlin supports recursion
which means a Kotlin function can call itself.
Syntax:-
fun functionName(){
...
functionName()
...
}
Example:-
Following is a Kotlin program to calculate the factorial of number 10:
fun main(args: Array<String>) {
val a = 4
26 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
fun factorial(a:Int):Int{
val result:Int
return result
}
output:
24
Kotlin Tail Recursion
A recursive function is eligible for tail recursion if the function call to
itself is the last operation it performs.
Example:
Following is a Kotlin program to calculate the factorial of number 10 using
tail recursion. Here we need to ensure that the multiplication is done
before the recursive call, not after.
27 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
}
fun factorial(a: Int, accum: Int = 1): Int
{
val result = a * accum
return if (a <= 1)
{
result
}
else
{
factorial(a - 1, result)
}
}
output:
24
28 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Higher-Order Functions
A higher-order function is a function that takes another function as
parameter and/or returns a function.
Example:
Following is a function which takes two integer parameters, a and b and
additionally, it takes another function operation as a parameter:
fun main(args: Array<String>)
{
val result = calculate(4, 5, ::sum)
println( result )
}
fun sum(a: Int, b: Int) = a + b
fun calculate(a: Int, b: Int, operation:(Int, Int) -> Int): Int {
return operation(a, b)
}
output:
9
Here we are calling the higher-order function passing in two integer
values and the function argument ::sum. Here :: is the notation that
references a function by name in Kotlin.
Example:
more example where a function returns another function. Here we
defined a higher-order function that returns a function. Here (Int) ->
Int represents the parameters and return type of the square function.
fun main(args: Array<String>) {
val func = operation()
println( func(4) )
}
29 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
}
output:
HELLO, WORLD!
30 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
}
inline fun myFunction(function:()-> Unit){
println("I am inline function - A")
function()
31 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
List listOf()
listOf<T>()
Map mapOf()
Set setOf()
Example
fun main() {
val numbers = listOf("one", "two", "three", "four")
32 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
println(numbers)
}
When you run the above Kotlin program, it will generate the following output:
[one, two, three, four]
Kotlin Mutable Collection
Mutable collections provides both read and write methods.
List ArrayList<T>()
arrayListOf()
mutableListOf()
Map HashMap
hashMapOf()
mutableMapOf()
Set hashSetOf()
mutableSetOf()
Example
fun main() {
val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five")
println(numbers)
}
output:
[one, two, three, four, five]
33 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Inheritance
The main class is called super class (or parent class) and the class which
inherits the superclass is called subclass (or child class). The subclass
contains features of superclass as well as its own.
In Kotlin, the derived class inherits a base class using: operator in the class
header (after the derive class name or constructor)
For example:
Inheritance Example:-
34 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Output:
Name is Ashu.
Age is 25
Salary is 40000.0
programming is my passion.
Name is Ajay.
Age is 24
Salary is 30000.0
travelling is my hobby.
35 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Abstract class or abstract function does not need to annotate with open
keyword as they are open by default. Abstract member function does not
contain its body. The member function cannot be declared as abstract if
it contains in body in abstract class.
Example:-
abstract class Car{
abstract fun run()
}
class Honda: Car(){
override fun run(){
println("Honda is running safely..")
}
}
fun main(args: Array<String>){
val obj = Honda()
36 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
obj.run();
}
Output:
Output:
Car is running..
Honda City is running..
37 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Kotlin Interface
An interface is a blueprint of class.Kotlin interface is similar to Java 8. It
contains abstract method declarations as well as implementation of
method.
Defining Interface
For example:
interface MyInterface {
val id: Int // abstract property
fun absMethod()// abstract method
fun doSomthing() {
// optional body
}
}
The methods which are only declared without their method body
are abstract by default.
Implementing Interfaces
interface MyInterface {
var id: Int // abstract property
fun absMethod():String // abstract method
fun doSomthing() {
println("MyInterface doing some work")
}
38 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
}
class InterfaceImp : MyInterface {
override var id: Int = 101
override fun absMethod(): String{
return "Implementing abstract method.."
}
}
fun main(args: Array<String>) {
val obj = InterfaceImp()
println("Calling overriding id value = ${obj.id}")
obj.doSomthing()
println(obj.absMethod())
}
Output:
interface MyInterface1 {
fun doSomthing()
}
interface MyInterface2 {
fun absMethod()
}
class MyClass : MyInterface1, MyInterface2 {
39 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
Output:
o public
o protected
o internal
o private
public modifier
40 | P a g e
Prepared By : Bhartiba Parmar
SHREE SWAMI VIVEKANAND COLLEGE
SURENDRANAGAR
protected modifier
internal modifier
The internal modifiers are newly added in Kotlin, it is not available in Java.
Declaring anything makes that field marked as internal field. The internal
modifier makes the field visible only inside the module in which it is
implemented.
private modifier
A private modifier allows the declaration to be accessible only within the block
in which properties, fields, etc. are declare. The private modifier declaration
does not allow to access the outside the scope. A private package can be
accessible within that specific file.
42 | P a g e
Prepared By : Bhartiba Parmar