-
Notifications
You must be signed in to change notification settings - Fork 1
2. Kotlin Basics
var nameofvar:Int =5 // Variable declaration syntax
val nameofval:Int =5 // Value declaration syntax
// Variables can be changed while values can not be
for(i in 1..5){
}
for(i in 1.rangeTo(5)){
}
// above loops are in range 1 to 5
for(i in 10.downTo(1)){
}
// the above loop ranges in decreasing order from 10 to 1
for(i in 1..10 step 2 ) // 1, 3, 5, 7, 9
Kotlin is a null safe language! It can not hold null values by default unless explicitly mentioned.
val x:Int = null //Throws an error
val x:Int ?= null //Suffixing ? to a type accepts null
// Since the '?' operator is used for specifying nullability,
// conditional operator does not exist in kotlin
val b: String? = null
println(b?.length)// '?.' safe call operator
This returns b.length
if b
is not null, and null otherwise. The type of this expression is Int?
.
When we have a nullable reference b
, we can say "if b
is not null, use it, otherwise use some non-null value":
val l = b?.length ?: -1 // '?:' elvis operator
// here b will use -1 if it is null
val l = b!!.length
The not-null assertion operator (!!
) converts any value to a non-null type and throws a NPE if the value is null. 😈
If you have a collection of elements of a nullable type and want to filter non-null elements, you can do so by using filterNotNull
:
val nullableList: List<Int?> = listOf(1, 2, null, 4)
val intList: List<Int> = nullableList.filterNotNull() //1,2,4
Unlike other languages, the if..else
statement in Kotlinhas the ability to assign a variable from the returned value of the if..else statement.
val number = 13
val result = if (number % 2 == 0) {
print("$number is divisible by 2")
} else {
print("$number is not divisible by 2")// 13 is not divisible by 2
} // result has the value "13 is not divisible by 2"
Alternate of switch
in other languages.
val number = 2
when (number) {
1 -> println("number is 1")
2 -> { //enclosed in braces for multiline body
println("number is 2")
println("it is an even number")
//this will be executed
}
3,4 -> println("number is 3 OR 4") //values can also be combined
}
// when can also work without any argument like this
when {
number == 1 -> println("it is one")
number == 2 -> println("it is two")
}
Above function can also be written as
fun add(a: Int, b: Int) = a + b
- An extension function is a member function of a class that is defined outside the class.
fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1)