Kotlin Assignment
Kotlin Assignment
// In Kotlin, we don’t require usage of class explicitly to make our application run
val myNumber = 10 // Int -> explicit declaration of Int not required for Initialization
var myDecimal = 1.0 // Float
var isActive = true // Boolean
var myString: String // Mutable String & for declaration explicit type need to mention
myString = "Hello World"
myString = "Another World" // var <-> mutable, val <-> Immutable
print(myNumber)
}
println("Str name is $str and length is ${str.length}") //Str name is hello vivek and length is 11
val a = 10
val b = 5
println("The sum of $a and $b is ${a + b}") // The sum of 10 and 5 is 15
var r3 = 5 downTo 1 step 2 // The range contains 5,3,1 - two values has difference of 2
var r4 = 'a'..'z' // The range contains values "a" , "b" , "c" .... "Z"
var r5 = 1.rangeTo(10)
}
IF as Expression
var a = 2
var b = 5
var maxValue: Int
if (a > b)
maxValue = a
else
maxValue = b
println(maxValue) // prints 5
var max: Int = if (a > b) // In kotlin we can directly assign the value from If
a
else
b
println(max) // prints 5
}
When as Expression
var x = 3
when (x) // in c and Java we have switch but in Kotlin we use when
{
1 -> println("x is 1") // ( case 1: ) in java in kotlin ( 1 -> )
2 -> println("x is 2")
in 3..20 -> println("x in between 3 and 20") // ranges can also be used
else -> {
println("x is unknown") // If we have multiple statements put that in block
println("x is $x") // Instead of default we use else
}
}
}
For Loop
var a = 1..10
for(i in a)
println(i) // prints 1 to 10
for(i in a step 2)
println(i) // prints 1,3,5,7,9 because we used step 2 so increment by 2
}
Function as Expression
MyFirst.kt
MyJava.java
// No matter the sequence of parameters inside main if we assign to actual arguments name
Extension Function -
fun main(args: Array<String>) {
// This function will behave like a function present inside the class student
{
return marks > 95
}
class myClass(name: String, id: Int) { // primary constructor does not have any code
val e_name: String
var e_id: Int
init{ // init block used to initialize the code
e_name = name
e_id = id
println("Name = ${e_name}")
println("Id = ${e_id}")
}
}
fun main(args: Array<String>){
val myclass = myClass ("Ashu", 101)
}
//class myClass(name: String, id: Int) // the name and id can’t be used inside class they just need to used for assigning to
another field variable inside init block (they are not properties of class)
/class myClass(var name: String , val id: Int) // the name and id can be used anywhere in the class
// var and val is not possible in Secondary constructor these parameters can’t be modified and can’t be used
anywhere
Calling one secondary constructor from another secondary constructor of same class
class MyClass {
// this executes first even calling above constructor because of using this() in above constructor
Inheritance: By default Classes are : public & final , For inheritance you need to make class open
fun doProgram() {
println("Programming is my passion.")
}
}
Abstract Class -All the variables (properties) and member functions of an abstract class are by default non-
abstract. So, if we want to override these members in the child class then we need to use open keyword .
//abstract class
abstract class Employee(val name: String, val experience: Int) { // Non-Abstract
// Property
// Abstract Property (Must be overridden by Subclasses) property can’t be declared
abstract var salary: Double
// Non-Abstract Method
fun employeeDetails() {
println("Name of the employee: $name")
println("Experience in years: $experience")
println("Annual Salary: $salary")
}
}
// derived class
class Engineer(name: String, experience: Int) : Employee(name, experience) {
override var salary = 500000.00
override fun dateOfBirth(date: String) {
println("Date of Birth is: $date")
}
}
Interface Properties and Methods in interface are abstract by default unlike abstract class (Not abstract by
default), Normal methods are public and open by default but NOT FINAL unlike abstract class (final and public
not open) , supports functionality of multiple inheritance.
fun onClick() { // Normal methods are public and open by default but NOT FINAL
println("MySecondInterface: onClick")
}
}
Tailrec Functions - recursion which performs the calculation first, then makes the recursive call
Lambda Expressions
We must explicitly declare the type of our lambda expression. If lambda returns no value then we can
use: Unit
Pattern: (Input) -> Output
Lambdas examples with return type –
▪ val lambda1: (Int) -> Int = (a -> a * a)
▪ val lambda2: (String, String) -> String = { a , b -> a + b }
▪ val lambda3: (Int)-> Unit = {print(Int)}
Higher Order Functions - function which can accepts a function as parameter or can returns a function
// higher-order function
fun higherfunc(lmbd: () -> Unit) { // accepting lambda as parameter
lmbd() // invokes lambda expression
}
Anonymous Functions- similar to a regular function except for the name of the function which is omitted
from the declaration. The body of the anonymous function can be either an expression or block.
Listof()
var intList = listOf<Int>(24, 3, 78, 64) // list is immutable we can't increase or decrease size
for (index in intList) { // $ sign to get direct value instead of concatenation
print("$index,") // prints 24,3,78,64
}
println()
println(stringList.get(0)) // Ajay
println(stringList.indexOf("Vijay")) // 1 -> first Index
println(stringList.lastIndexOf("Vijay")) // 3 -> last Index having vijay
println(stringList.size) // 5 -> size of list
println(stringList.contains("Prakash")) // if contains return true
println(stringList.subList(2, 4)) // [Prakash, Vijay] -> from index 2 to 4 less 1
println(stringList.isEmpty()) // false -> if empty return true
println(stringList.drop(1)) // prints elements in List except last 1
println(stringList.dropLast(2)) // prints elements in List except last 2
println(stringList)
val sortlist = intList.sorted(); // list is mutable we can't apply sorting to list itself
println(sortlist); // [3,24,64,78]
}
ArrayListOf()
import java.util.*
import kotlin.collections.ArrayList
println(arrayList.size) // 5
println(arrayList.get(2)) // prakash prints index of 2 element in list
arrayList.set(3, "Ashu") // Mutable array we can modify elements
println(arrayList[3]) // prints Ashu
println(arrayList.indexOf("Vijay")) //1 -> first occurence Index having vijay
println(arrayList.lastIndexOf("Vijay")) //4- > last Index having vijay
arrayList.remove("Vijay") // removes vijay of first occurence
// arrayList.removeAt(index)
println(arrayList) // [Ajay, Prakash, Ashu, Vijay] after removing vijay
arrayList.clear() // to clear all elements in arraylist
println(arrayList) // [ empty array ] after clearing all elements
println(intList) // [5, 9, 1, 3, 4, 7]
val a = intList.sortedDescending() // sorted in descending order
println(a) // [9, 7, 5, 4, 3, 1] - > sort in descending order
val itr = intList.iterator() // using iterator for printing elements in list
while (itr.hasNext()) {
println(itr.next())
}
}
MapOf() - key and value pair. Map keys are unique and hold only one value for each key. The key and value may
be of different pairs such as <Int, Int>,<Int, String>, <Char, String>etc. This interface is immutable, fixed size and
its methods support read only access.
myMap.plus(Pair(5, "Rohan"));
println(myMap) // {1=Ajay, 4=Vijay, 3=Prakash} mutable we can't add to myMap
import java.util.*
import kotlin.collections.HashMap
}
Setof() -unordered collection of elements, does not support duplicate elements.
val remainList = mySet.drop(4) // drops first 4 elements from set and copy all other to remainList
println(remainList) // [5, Ashu, Ajay]
import java.util.*
import kotlin.collections.HashSet
println("Enter elements")
for (i in 0..2) {
hashSet.add(read.nextInt()) // reading input from user
}
println("......hashSet......")
for (element in hashSet) {
println(element)
}
hashSet.remove(2)
hashSet.removeAll(intSet)
println(hashSet) // [1, 8] - > after removing intList and (remove(2))