Let’s start with some basic things about Kotlin. If you have programmed in any other language before, then this should be a good place to begin.
Numbers
In Kotlin, int is a primitive type.
All numeric values have super type called Number. It is implicitly done so no need to do it. If you are not storing numbers in an object then you don’t need to create the wrappers (define it); if you do store numbers you have to do it (create an object ie wrap it). This is called boxing. Example:
Not boxing : 1.toLong()
Boxing : val boxed: Number = 1
boxed.toLong()
Kotlin supports underscore in numbers so you can use wherever you want and whatever makes sense to you. Ex : val oneMillion = 1_000_000
Val
You can assign value once using val. If you assign it again you get error.
Example :
val aquarium =1
aquarium =2 // gives **error**
Val can allow manipulation of list items, but it wont allow you to assign new list to your list if it is declared as val.
Var
The assignment done to var can be changed.
Type of the var and val can be determined by the compiler based on the context.
var aquarium =1
aquarium =2 // works
Casting
Kotlin wont do Number casting implicitly. You can’t assign one type of Number to another. You have to cast it.
Example :
val b : Byte = 1
val i : Int = b //gives **error**
However, val i : Int = b.toInt() // **compiles**
However, val i : Int = b.toInt() // compiles
Null assignment And the question mark (?) operator
If you declare a var, you can’t declare it to Null. You can use the (?) operator to define that this variable might be null, ie nullable.
Ex : var marbles : Int? = null
For list you can use ? to define if it is Null or not. If the list type is not null then elements can’t be null.
Ex : var lotsOfFish : List<String?> = listOf(null,null)
Not Know Assertion (!!)
The not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null. Thus, if you want an NPE, you can have it, but you have to ask for it explicitly and it won’t appear out of the blue.
Ex : val l = b!!.length //will throw NPE if b is null.
Elvis Operator ( ?: )
You can use this ?: operator to check if something is null and return appropriate value. Saves a lot of if else loops.
Ex : val l = b?.length ?: -1
In above ex, it will return b.length if it’s not null, if it is then it returns -1.
Boolean Operators
== → for equality check
! = → for not equal
Conditional Loops
- If- else : For normal if else
Ex : if(fish in 1..100) return “Fish exists!”
- When : Like Switch statement in java
Ex :
when(numberOfFish){
50 → println("Fifty fishes")
in 50..80 → println("Between 50 & 80")
100 → println("Hundred Fishes")
else → println("Default statement")
}
//Notice : No break;
when can also be used using no arguments
return when
{
temperature>30 -> "Too hot"
dirtyPercent>20 -> "Dirty"
day=="Sunday" -> "Sunday"
}
Notice how we haven’t passed any args to when and when can be used as replacement for multiple if else statements.
For loop
- for(element in nestedArray) println(element)
- for((index,element) in nestedArray.withIndex()){ println(“Fish in $index is $element”) }
- Ranges :
- In alphabets : for (i in b..g) print(i) ⇒ O/p bcdefg
- In number : for (i in 1..3) print (i) ⇒ o/p 123
- Range going downwards : for( i in 5 downTo 1) print (i) ⇒ o/p 54321
- Range down in multiple steps : for( i in 3..6 step 2) print (i) ⇒ o/p 35
Arrays :
- Create an array with arrayOf method.
Ex : val short = arrayOf(1,2,3)
O/p: [1,2,3]
Ex : val fishes = arrayOf("tuna","salmon","piranha")
o/p : ["tuna","salmon","piranha"]
- Mix Type Arrays are allowed
Ex: val mix = arrayOf("fish",2)
print(Arrays.toString(mix))
- Nested Arrays
Ex : val nestedArray = arrayOf(fishes, mix, arrayOf("fish", "mixes"))
println(Arrays.toString(nestedArray))
- Declare Array with it
Ex : val arr = Array(5) {it*2}
0,2,4,6,8
Or
Ex : val array = Array(7) { 1000.0.pow(it) }
Use of double to get the pow function and this gives us 1000 (to the power of index at each index)
So the array would be : [1000^0 , 1000^1, …. 1000^6]
[1,1000,1000000,…1000000000000000000]
Hope this will get you started on basics of Kotlin. Stay tuned for more upcoming Kotlin posts.
Keep learning, keep creating! 🙂
One thought on “Learn Kotlin #1 : Types, Operators, Arrays And Loops”