Kotlin Guide to Code, Conditions, and Null Safety

Kotlin Guide to Code, Conditions, and Null Safety

ยท

5 min read

Kotlin is considered the official Android Language, and Android development in today's time takes a Kotlin-First Approach.

  • Concise and Safer Code

  • Interoperable with Java


๐Ÿ“ Print

print(42)
print("hello world")
val i = 10
val j = "as"
println(i) // prints and leaves a new line
print("$j") 
print(j)
/* Multi Line
Comment */

๐Ÿ”ข Variable Declaration & Data Types

Two different keywords var and val are used to declare variables in Kotlin.

val is used for read-only values that you do not want to reassign later i.e. Immutable values. Whereas, var is used for Mutable values and can be reassigned.

val a : Int = 5 
val b  = 10 // no need to mention the type
val c : Int // need to mention the type
c = 15

a = 10 //Fails to Compile

var d = 10
d = 15 //Successfully compiles

Int represents that the variable is of the type Integer. Kotlin compiler can automatically infer the type of variable based on the assigned value, hence no need to declare the datatype of the variable when the value is assigned at the same step.

Kotlin is a statically typed language, which means the type of the variable is resolved at the compile time. Hence, any discrepancy in the code will fail to compile.

val name = "vedant" 
val nameUppercase = name.toUppercase() //will compile successfully
nameUppercase.inc() //will fail to compile as inc() is a function of the Integer class

Different Data Types in Kotlin:

  • Numeric(Byte, Short, Int, Long, Float, Double)

    The default type considered is Int or Long(use L or l with the value) for integer value depending on its size and default value is double for decimal value, (use F or f for floating value)

    Explicit Conversion of datatype can be done by functions like toByte(), toInt(), etc. Implicit Conversion takes place according to the computational result. eg: Long + Int returns Long

  • Boolean (Boolean)

    true or false values

  • Characters(Char, String)

    Characters are enclosed in single quotes ' ' . If the character value is an Integer, it can be converted into an Integer using digitToInt() function. Special characters starting from a / eg. /n represents a new line.

    String is a sequence of characters enclosed in double quotes " " . Multi-Line strings are enclosed in triple quotes """ """ . Strings are immutable i.e can't reassign values to a string variable. String characters are accessed through indexes. String literals can contain template expressions, which is a piece of code that needs to be evaluated, needs to be enclosed in { } if it is an expression.

      val rollNo = "50"
      print("Your Roll Number is: $rollNo")
      print("Your Roll Number is: ${rollNo/10}")
    
  • Array

    More about Arrays in Collections

Kotlin is similar to Java, and has all the basic operators used in Java like + - * / % == >= etc. || && ! for comparison.


๐Ÿ”„ Conditions & Loops

Conditional Branches if, if-else works the same way as they do in Java. However, there is no ternary operation in Kotlin.

if (count == 42) {
    println("I have the answer.")
} else {
    println("The answer eludes me.")
}
if (count == 42) {
    println("I have the answer.")
} else if (count > 35) {
    println("The answer is close.")
} else {
    println("The answer eludes me.")
}

Conditional expressions can be used in Kotlin to assign values to variables based on conditions.

val answerString: String = if (count == 42) {
    "I have the answer."
} else {
    "I don't have the answer."
}

Similarly, when block can be used to define conditional expressions.

val answerString = when {
    count = 50 -> "Value is 50"
    count == 40, count == 30 -> "I have the answer."
    in 10..20 -> "Lies between 10 and 20."
    else -> "The answer eludes me."
}

while and do-while loops work the same way as they do in any other language.. and have the same syntax as in Java.

while (x > 0) {
    x--
}
val y = 10
do {
    y++
} while (y != 15) // y is visible here!

for loop is used to iterate through anything that provides an iterator.

for (item in collection) ... task ...

for(i in 0..10){ /*runs from 0,1,..10*/ }
for(i in 0 until 10){ /*runs from 0,1,..9*/ }
for(i in 10 downTo 0){ /*runs from 10,9..0*/ }
for(i in 10 downTo 0 step 2){ /*runs from 10,8,6..0*/ }
for(i in arr){ /*iterates through elements of array*/ }
for(i in arr.indices){ /*iterates through indexes 0,1,.. of array*/ }

break and continue have the same functioning and syntax as they do in any other language and are used to exit the loop and jump to the next iteration in the loop respectively.


๐Ÿ—‘๏ธ Null Safety

Unlike Java, Kotlin variables can't hold null values by default. An unassigned object points to null when any instruction is carried out on it. For a variable to hold a null value in Kotlin, it should be of a nullable type.

val languageName: String = null // Fails to compile
val languageName: String? = null

This guarantees us that there won't be Null Pointer Exception for any variable which is of the type Not Nullable, and measures can be taken for instructions on Nullable type to avoid NPE.

var b: String? = "abc" // can be set to null
b = null // ok
val a = "xyz"
var l = a.length //works fine as gaurantee of no NPE
l = b.length // error: variable 'b' can be null
l = if (b != null) b.length else -1 //thus check nullability of variable

๐Ÿ“ฆ Package & Import

A source file might start with a package declaration, which states that all the functions and classes of that source file are enclosed inside that package, and can be accessed by the package name followed by the block name.

package org.example

fun printMessage() { /*...*/ }
class Message { /*...*/ }

printMessage() function can be accessed by org.example.printMessage

Message class can be accessed by org.example.Message

Kotlin Code File imports many parent packages by default. Apart from these default imports, we can include our own import directives in the code file.

import org.example.Message // Message is now accessible 
import org.example.* // everything in 'org.example' becomes accessible
import org.example.printMessage as chat// Message is accessible as chat

ย