Kotlin | Top Ten Things To Know
By: Angry Red Cat
Tags: Android, Java, Kotlin Beginners, Android App Development, Kotlin

Here We Go👈👈👈

No more Semi Colon ;

2. Variable declaration: Can be either var (read/write) or val (read only).

val a: Int = 1 // immediate assignment

val b = 2 // `Int` type is inferred

val c: Int // Type required when no initializer is provided

c = 3 // deferred assignment

val oneMillion = 1_000_000 // Can use underscores for readability

3. Defining functions: Functions can be defined by fun keyword and can be top-level, no need to put everything inside a class. Also functions can be passed around just like any other type and used as argument of functions.

// Function with params and return type

fun sum(a: Int, b: Int): Int {

return a + b

} // Function with params and no-return type

fun printSum(a: Int, b: Int) {

println("sum of $a and $b is ${a + b}")

}

4. Null Safety (The Billion Dollar mistake fix): In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references).

Using safe call operator (?)

private var number: Int? = null // Here we are telling compiler that number can have null value. By, default any variable cannot be null in kotlin.

Using the not-null assertion operator ( !! ).

This option is for NPE-lovers. If we want an NPE, we can have it, but you have to ask for it explicitly using ( !! ), and it does not appear out of the blue.

val l = b!!.length // converts any value to a non-null type and throws an exception if the value is null

Checking for null with Elvis Operator.

val x= b?.length ?: -1 //We can use Elvis Operator instead of if-expression

Safe Casts. Regular casts may result into a ClassCastException if the object is not of the target type.

val aInt: Int? = a as? Int // Using safe casts will return null if the attempt was not successful

Function that returns null. Marking the return type with (?) as nullable when null value is possible.

// Return null if str does not hold an integer:

fun parseInt(str: String): Int? {

// …

}

5. Using conditionals: Pretty much similar to all the languages except notable for switch statements which is done by when statements.

: if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

// Traditional Usage

var max: Int

if (a > b) {

max = a

} else {

max = b

}



// As expression

val max = if (a > b) a else b

: for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#

// for loop

for (item in collection) print(item)

: while and do..while work as usual

// while loop

val items = listOf("apple", "banana", "kiwi")

var index = 0

while (index < items.size) {

println("item at $index is ${items[index]}")

index++

}

: when replaces the switch operator of C-like languages. whencan be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression.

If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions.

//Switch(When) Condition when(view.visibility){

View.VISIBLE -> toast("visible")

View.INVISIBLE -> toast("invisible")

else -> toast("gone")

}

6. No need of “new” keyword:

val rectangle = Rectangle(5.0, 2.0) //no ‘new’ keyword required

val triangle = Triangle(3.0, 4.0, 5.0)

7. No “Static” keyword, that doesn’t mean that we can’t reap the benefits provided by static methods in Kotlin.

We should use package-level functions if we want to follow DRY, then we can import the function anywhere and use it there.

8. A brand new “Data” class, whose main purpose is to hold data. Avoid the boilerplate we need in Java. Apart from getters and setters we get equals(), hashCode() & copy() for free.

data class User(val name: String, val age: Int)

9. Lateinit (not Lazy). Every non-nullable class property that is declared in the class needs to be assigned in the constructor; otherwise, we’ll get a compiler error.

To defer initialization of the variable, we can specify that a field is lateinit. We are informing the compiler that this will variable will be assigned later and we are freeing the compiler from the responsibility of making sure that this variable gets initialized:

private lateinit var value: MyClass



fun init(externalProperties: Any) {

value = somethingThatDependsOn(externalProperties)

}

10. Type comparison with “is” and “as”. To check if an object is of a specific type you can use the “is” expression.

if (obj is Double) // Check is the obj a Double

println(obj + 3.0) if (obj !is String){ // make sure obj is not a string

println(obj)

}

To cast an object there is the “as” operator. This operator has two forms: the safe and unsafe cast.