You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To indicate the storage area, each variable should be given a
unique name (Identifier).
Control Flows
Do something conditionally
To repeatedly run code conditionally.
Functions
Functions enable us to separate code.
Run code blocks when needed.
Collections
Collections enable us to store multiple elements in one place.
Iterate through multiple elements (with the help of control
flows).
Classes and Objects (including inheritance)
Create our own data types
Keep the data members and methods together in one place.
Write more readable and maintainable code.
Work better in a team.
Variables and Data Types
There is two types of variables in kotlin
Mutable
var aquarium =1
aquarium =50
Immutable
val fish ="Nemo"
Immutable list can not reassign new value but can be manipulate
list.
val myList = mutalbleListOf("tuna", "salmon", "shark")
myList.remove("shark")
Byte
val myByte:Byte=13
Short
val myShort:Short=125
Int
val myInt:Int=12345678
Long
val myLong:Long=12_123_123_123_1234
Float
val myFloar:Float=13.43F
Double
val myDouble:Double=3.1233445535445
Boolean
val myBoolean:Boolean=true
Char
val myChar:Char='A'
String
val myString:String="Shafiqur Rahman"
Arithmetic Operators
(+, -, /, *, %)
int divide by int returns int
float divide by float returns float
1/2// Will return 01.0/20. // Will return 0.5
Arithmetic Methods
val fish =2
fish.times(6)
fish.div(10)
fish.plus(3)
fish.minus(3)
Boxing
1.toLong()
val boxed:Number=1
boxed.toLong()
Comparison Operators
(==, !=, <, >, <=, >=)
Null Safety
Add ? to indicate variable can contain null value
var marble:Int?=nullvar lotsOfFish:List<String?> =listOf(null, null)
var evenMoreFish:List<String>?=nullvar definitelyFish:List<String?>?=null
Force a null able type in kotlin
goldfish!!.eat()
Null check operator ?: Elvis Operator
return fishFoodTreats?.dec() ?:0
Safe Call Operator ?.let
var nullableName:String?="Pallab"
nullableName?.let { println(it.length) }
Chain Null check
val age:String?= user?.wife?.age ?:0
Switch with When
var welcomeMessage ="Hello and welcome to Kotlin"when (welcomeMessage.length) {
0, 1->println("Nothing to say?")
in2..50->println("Perfect")
else->println("Too long!")
}
var fish =12var plants =5val swam =listOf(fish, plants)
val bigSwarm = arrayOf(swam, arrayOf("Dolphin", "Whale", "orka"))
println(Arrays.toString(bigSwarm))
Array comprehension
val array =Array(5) { it *2 }
println(array.asList())
Array of data class
data classFruit(valname:String, valprice:Double)
val fruits = arrayOf(Fruit("Apple", 2.5), Fruit("Grape", 3.5))
for (fruit in fruits){
println("${fruit.name}")
}
for(index in fruits.indices){
println("${fruits[index].name} is in index $index")
}
Array List
Array List are used to create a dynamic array. Which means the
size of an array can be increased or decreased according to
requirement.
The Array List class provide both read and write functionality
The Array List follows the sequence of insertion order.
An array is non synchronized and it may contain duplicate element.
ArrayList<E>(): Is used to create an empty Array List.
ArrayList(capacity: Int): Is used to create an Array List of
specified capacity.
ArrayList(elements: Collection<E>): Is used to create an Array
List filled with the elements of a collection.
open fun add(element: E): Boolean -> used to add the specific
element into the collection.
open fun clear() -> used to remove all elements from the collection.
open fun get(index: Int): E -> used to return the element at
specific index in the list.
open fun remove(element: E): Boolean -> used to remove a single
instance of the specific element from current collection, if it is
available.
Empty Array List
funmain() {
val arrayList =ArrayList<String>()
arrayList.add("One")
arrayList.add("Two")
for(i in arrayList){
println(i)
}
}
Array List using collection
funmain() {
val arrayList:ArrayList<String> =ArrayList<String>(5)
var list:MutableList<String> = mutableListOf<String>()
list.add("One")
list.add("Two")
arrayList.addAll(list)
val itr = arrayList.iterator()
while (itr.hasNext()) {
println(itr.next())
}
println("Size of array list = ${arrayList.size}")
}
Array List get
funmain() {
val arrayList:ArrayList<String> =ArrayList<String>()
arrayList.add("One")
arrayList.add("Two")
for (i in arrayList) {
println(i)
}
println(arrayList.get(1))
}
List (Collections)
// List of Stringsval stringList:List<String> =listOf(
"Denish", "Frank", "Michael", "Greater"
)
// List of Mixed Typeval mixedTypeList:List<Any> =listOf(
"Denish", 31, 5, "Bday", 70.5, "KG"
)
val months =listOf("January", "February", "March")
val additionalMonths = months.toMutableList()
val newMonths = arrayOf("April", "May", "June")
additionalMonths.addAll(newMonths)
additionalMonths.add("July")
print(additionalMonths)
val days = mutableListOf<String>("Saturday", "Sunday", "Monday")
print(day)
Map (Collections)
val fruits =setOf("Orange", "Apple", "Mango", "Apple", "Grape", "Orange")
print(fruits.size)
// mapOf key, valueval daysOfTheWeek =mapOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday")
for(key in daysOfTheWeek.keys){
println("$key is to ${daysOfTheWeek[key]}")
}
data classFruit(valname:String, valprice:Double)
val fruitsMap =mapOf(
"Favorite" to Fruit("Mango", 2.5),
"Okay" to Fruit("Apple", 1.0)
)
For Loop
looping without index
for (element in swarm) println(element)
looping with index
for ((index, element) in swarm.withIndex()){
println("Fish at $index is $element")
}
Ranges print
for (i in'b'..'g') println(i)
for (i in1..120) println(i)
for (i in5 downTo 1) println(i)
for (i in5 downTo 1 step 2) println(i)
for (i in3..6 step 2) println(i)
for (i in1 until 10) println(i)
For Each
While Loop
var x =1while(x <=10) {
println("$x")
x++
}
println("While loop is done.")
Do While Loop
x =15do {
print("$x")
x++
} while(x <=10)
Repeat Loop
Filter
Eager Filter (Create a new list)
val decorations =listOf(
"rock", "pagoda", "plastic plant", "alligator", "flowerpot"
)
val eager = decorations.filter { it[0] =='p'}
println(eager)
Lazy Filter
val decorations =listOf(
"rock", "pagoda", "plastic plant", "alligator", "flowerpot"
)
val filtered = decorations.asSequence().filter() { it[0] =='p' }
println(filtered)
println(filtered.toList())
lambda
Lambda (Expression) is a function which has no name.
Lambda expression and anonymous functions are ‘function literals’
i.e. functions that are not declared, but passed immediately as an
expression.
Lambda is defined with curly braces {} which takes variables as a
parameter (if any) and a body of a function.
The body of a function is written after the variable (if any)
followed by -> operator.
Syntax : {variable(s) -> body_of_lambda}
A value assigned at compile time, and the value never changes when
the variable is accessed.
a lambda assigned at compile time, and the lambda is executed
every time the variable is referenced, returning a different
value.
Example:
val sum: (Int, Int) ->Int= { a:Int, b:Int-> a + b }
pritln(sum(10, 5))
// Even Shorterval sum = { a:Int, b:Int->println(a + b) }
sum(10, 15)
Classes
Simple way to create a class
classPerson constructor(_firstName:String, _lastName:String) {
// Member Variable (Properties) of the classvar firstName:Stringvar lastName:String// Initializer Blocksinit {
this.firstName =_firstNamethis.lastName =_lastNameprintln("First Name: $firstName")
println("Last Name: $lastName")
}
}
funmain() {
val pallab =Person("Pallab", "pal")
println(pallab)
}
More Simple way to create a class
classPerson(_firstName:String, _lastName:String){
// Member Variables (Properties) of the classvar firstName:String=_firstNamevar lastName:String=_lastName// Initializer Blockinit {
println("FirstName = $firstName and LastName = $lastName")
}
}
funmain() {
val pallab =Person("Pallab", "pal")
println(pallab)
}