- Hello World
- var vs val
- Data Types
- Null Safety
- Different types of function declarations
- Elvis Operator
- When - An alternative to else-if ladder
Hello World Back ⇈
fun main() {
println("Hello World!")
var vs val Back ⇈
var
is used to declare a mutable variable i.e value can be changed.
val
is used to declare an immutable variable i.e value can't be changed.
var name: String = "Sam" // mutable
name = "Abhishek"
val anotherName: String = "Sam" // immutable
anotherName = "Abhishek" // compilation error
Data Types Back ⇈
- String
- Boolean
- Byte
- Short
- Int
- Long
- Float
- Double
val name: String = "Hello world!"
val isVerified: Boolean = true // or false
val byte: Byte = 20
val one: Int = 1
val number: Long = 123456789
val floatNumber: Float = 123.52f
val pi: Double = 3.14
Null Safety Back ⇈
Kotlin has a strong type system which means, variables can either hold null or they can't.
var name: String = "John Doe"
name = null // invalid (error)
var nullableName: String? = "John Doe"
nullableName = null // valid
var age: Int = null // invalid (error)
var nullableAge: Int? = 10
nullableAge = null // valid
val students = mutableListOf<String>()
students.add(null) // invalid (error)
val nullableStudents = mutableListOf<String?>()
nullableStudents.add(null) // valid
Different types of function declarations Back ⇈
There are multiple ways to declare functions in kotlin.
fun main() {
val num1 = 10
val num2 = 20
val sum = add(num1, num2) // 30
val difference = subtract(num1, num2) // -10
val product = multiply(num1, num2) // 200
val quotient = num2.divide(num1) // 2
val remainder = num2 % num1 // 0
}
fun add(num1: Int, num2: Int): Int { return num1 + num2 } // regular function
fun subtract(num1: Int, num2: Int): Int = num1 - num2 // like an expression
fun multiply(num1: Int, num2: Int) = num1 * num2 // return type is inferred
fun Int.divide(num2: Int) = this / num2 // extension function
Elvis Operator Back ⇈
'?:' is called an elvis operator and the value on the right of it is used when the value on the left of it is null.
val name: String? = null
var capitalizedName = name?.capitalize()
println("name: $capitalizedName") // null
capitalizedName = name?.capitalize() ?: "John Doe"
println("name: $capitalizedName") // John Doe
When - An alternative to else-if ladderBack ⇈
Tracking and understanding all the branches of else-if ladder can be a tricky job whcih can be simplified
fun main() {
val user = User("ABC", "def")
validateUser(user)
}
fun validateUser(user: User) {
when {
user.name == null -> logError("")
user.password == null -> logError("")
else -> {
validateUsername(user.name)
validatePassword(user.password)
}
}
}