0% found this document useful (0 votes)
0 views36 pages

02 - Basic Kotlin

This document provides an introduction to Kotlin, a statically typed programming language for the JVM and Android, highlighting its key features such as conciseness, safety, and interoperability. It covers fundamental concepts including variable declaration, data types, control structures (if..else, when, loops), null safety, functions, and arrays. Examples are provided to illustrate each concept, demonstrating how to use Kotlin effectively for Android development.

Uploaded by

namayheng12345
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)
0 views36 pages

02 - Basic Kotlin

This document provides an introduction to Kotlin, a statically typed programming language for the JVM and Android, highlighting its key features such as conciseness, safety, and interoperability. It covers fundamental concepts including variable declaration, data types, control structures (if..else, when, loops), null safety, functions, and arrays. Examples are provided to illustrate each concept, demonstrating how to use Kotlin effectively for Android development.

Uploaded by

namayheng12345
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/ 36

Chapter II

Basic Kotlin for Android


What is Kotlin?
Statically typed programming language for the JVM, Android and the browser.
(http://kotlinlang.org/)

Why Kotlin?

• Concise: drastically reduce the amount of boilerplate code you need to write.

• Safe: avoid entire classes of errors such as null pointer exceptions.

• Interoperable: leverage existing frameworks and libraries of the JVM with 100%
Java Interoperability.

2
Variable
In Kotlin variables can be declared using two keywords
namely val and var.

val: It is used for variables whose value never changes.


var: It is used for variable whose value can change.

Syntax:

Keyword varName: data_type=value

3
Variable-using val keyword,Example
val x: Int = 10

fun main( ){

println(x) // 10

Also when I try to reassign the variable value I will get an error indicating variable
value cannot be reassigned because I using val keyword.

val x: Int = 10
fun main( ) {
x = 20
println(x) // Error
}
4
Variable-using var keyword,Example
var x: Int = 10

fun main( ){

println(x) // 10

Also when I try to reassign the variable value I will not get an error this time variable
value can be reassigned because I using var keyword.

var x: Int = 10
fun main( ) {
x = 20
println(x) //20
}
5
Data Type
• Numbers Ex:
• Byte,Short, Int,Long, val num: Byte=10
Float, Double
println(num)

• Characters val age: Int = 28


• Char println(age)

• Booleans
• Boolean
6
Arithmetic Operators

7
Assignment Operators

8
Comparison Operators

9
Logical Operators

10
in Operator
• The in operator is used to check whether an object
belongs to a collection.

Ex:
fun main(args: Array<String>) {
val numbers = intArrayOf(1, 4, 42, -3)
if (4 in numbers) {
println("numbers array contains 4.")
}
}
11
Expressions
val score: Int

score = 90+25

Here, 90 + 25 is an expression that returns Int value.

fun main(agrs:Array<String>){

val a=12

val b=13

val max:Int

max = if(a>b) a else b

println(“$max”)

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

val time = 20

val greeting = if (time < 18) {

"Good day."

} else { "Good evening." }

println(greeting)

13
When Expression
The when construct in Kotlin can be thought of as a replacement for Java switch Statement.

fun main(args: Array<String>){

val a=12

val b= 5

println(“Enter operator either +,-,* or /”)

val opt = readline() else -> “$opt operator is Invalid!”


println(“result=$result”)
val result = when(opt){

“+” -> a+b }

“-” -> a-b

“*” -> a*b

“/” -> a/b


14
while Loop
• loops through a block of code as long as a specified condition
is true

Syntax:

while (condition) {

// code block to be executed

15
while Loop-Example
fun main(args: Array<String>) Output
{ 1
var i = 1 2
while (i<=5){ 3
println(i) 4
i++ 5
}
}

16
do while Example
Ex:
var i = 0
Output
0
do{ 1
2
println(i) 3
4
i++

}while(i<5)

17
for loop
• used to iterate a part of program several times. It iterates
through arrays, ranges, collections, or anything that
provides for iterate. Kotlin for loop is equivalent to
the foreach loop in languages like C#.

Syntax:
for (item in collection){
//body of loop
}
18
Iterate through array
Ex:
fun main(args : Array<String>) { Output
60
val marks = arrayOf(60,70,80,95,90) 70
80
for(item in marks){
95
println(item) 90

}
19
Iterate through array using index
Ex:
fun main(args : Array<String>) { Output
marks[0]:60
val marks: Array<Int>= arrayOf(60,70,80,95,90)
marks[1]:70

for(index in marks.indices){ marks[2]:80


marks[3]:95
println(“marks[$index]:”+marks[index]) marks[4]:90

}
20
Iterate through range
• using the .. Operator

• rangeTo() Operator

• step in Range

• downTo() function

21
Iterate through range –using ..
operator example
fun main() {
val range = 1..9
Output
if (1 in range) 1 is in
1..9
println("1 is in $range")
if(10 in range)
println("10 is in $range")
}
22
Iterate through range –using ..
operator example
fun main() {
Output
val range = 1..10 step 2 1
3
for (number in range)
5
println(number) 7
9
}

23
Iterate through range –using step
example
fun main() { Output
1
val range = 1..10 step 2
3

for (number in range) 5


7
println(number) 9

24
Iterate through range –using downTo
example
Output
fun main() { 10
9
val range = 10 downTo 1 8
7
6
for (number in range) 5
4
println(number) 3
2
1
}

25
Null Safety
Kotlin programming language variables cannot hold null
variables by default so in order to hold null variables
you have to use a different syntax as shown below, all
you have to do is you have to add a “?” in front of the
variable declaration.

26
Null Safety-Example
Ex:

var num: Int? = null

fun main( ) {

println(num) //null

27
Elvis Operator (?:)
• is used to return the not null value even the
conditional expression is null. It is also used to
check the null safety of values.

28
Elvis Operator (?:)-Example
fun main(args: Array<String>){

var str: String? = null

var str2: String? = "May be declare nullable string"

var len1: Int = str ?.length ?: -1


Output
var len2: Int = str2 ?.length ?: -1
Length of str is -1
println("Length of str is ${len1}")
Length of str2 is 30
println("Length of str2 is ${len2}")

} 29
Function
• are a block of organized and reusable code that is used to perform a single
task.

• In Kotlin in order to create a function you have to use the fun keyword

Syntax:

fun funName( ): data_type{

statement(s)

statement return

30
Function-Example
Ex1: Ex2:

fun sum( ): Int{


fun sum(a:Int,b:Int):Int{
val a: Int = 10
return (a+b)
val b: Int = 20 }

return (a+b)

}
fun main( ) {
fun main( ) { println(sum(10,20))
//30
println(sum())
}
}
31
Lambda and Anonymous Functions
• are called function that are not declared but, rather passed
immediately as an expression

• don’t need a name.


Lambda with parameters
Ex1:

val doThis={ Ex2:

println("action") { msg:String -> println("Hello


$msg") }

}
32
Array
• Arrays in Kotlin are able to store multiple values of different
data types.
• Of course if we want we can restrict the arrays to hold the
values of a particular data types. In this guide, we will discuss
about arrays in Kotlin.
Kotlin Array Declaration
Array that holds multiple different data types.
var arr = arrayOf(10, ”Hello”, 10.5, ’A’)

33
Array
Array that can only hold integers

var arr = arrayOf<Int>(1, 3, 5)

Array that can only hold strings

var arr = arrayOf<String>(“ab”, “item”,”hello”)

34
Array-Example
fun main(args: Array<String>) {

val fruits = arrayOf<String>("Apple", "Mango", "Banana",


"Orange")

println( fruits.get(0))

println( fruits.get(3)) // Set the value at 3rd index fruits.

set(3, "Guava")

println( fruits.get(3))

} 35
Thank You Calligraphy Transparent PNG | PNG Mart

36

You might also like