1. Why Kotlin for Android?

Birat Rai
4 min readDec 18, 2017

--

This is the first milestone towards our Kotlin series.

why kotlin?

What is Kotlin?

Kotlin is a statically typed programming language for building modern, multi-platform applications.

It was launched in 2011 by JetBrains.

Why Kotlin?

  • Open source: Under Apache 2.0 so it will evolve tremendously backed by JetBrains and now Google.
  • Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues.
  • Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure.
  • Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application..
  • Learning Curve: For a Java developer, getting started with Kotlin is very easy.
  • Support: Kotlin is fully integrated in Android Studio 3.0 and before that we could use Kotlin plugin to use in Android Studio.

What are the Basic Syntax?

  1. No more Semi;colon;
  2. Variable declaration: Can be either var (read/write) or val (read only). There is no primitive types in Kotlin. We use “Double”, “Int” etc instead.
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

2. Defining functions: Functions can be defined by fun keyword.

// 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}")
}

3. Using conditionals: Pretty much similar to all the languages except notable for switch statements which is done by when statements. Break and Continue are supported similarly as well.

// for loop
for (item in collection) print(item)
// while loop
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
// switch statements is replaced by when
private fun gettSuit(i: Int): String = when (i / 13) {
0 -> "Clubs"
1 -> "Diamonds"
2 -> "Hearts"
else -> "Spades"
}

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 l: Int = if (b != null) b.length else -1 // Null-value check with if-expressionval l = 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 Collections:

// Iterating over a collection
for (item in items) {
println(item)
}

6. Creating instance of classes:

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

7. Conditional if expressions: In Kotlin, 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.

fun maxOf(a: Int, b: Int) = if (a > b) a else b

The Second milestone in this series.

2. Hello Kotlin

References:

  1. Using Kotlin for Android development ~ Kotlin.org
  2. Resources to Learn Kotlin ~ developer.android
  3. Why switch to Kotlin? ~ Medium blog
  4. Variable types in Kotlin ~ Kotlin.org

--

--