Learn Kotlin gist for android developers part- 1

Md Ali Hossain
5 min readSep 21, 2018

--

Recently, I have started studying the book “Kotlin for Android Developers” for learning Kotlin specially as a android developer. And feels that it would be better if I grasp the gist from this book and why not make a series so that those(Android developer) are willing to learn kotlin and wants to convert their code from Java to Kotlin easily for their android project.

And here is the Part — 1 of my series. Will cover full “Kotlin for Android Developers” book gist part by part. Let me know any kind of feedback and suggestion.

Intro — 1

Java Virtual Machine (JVM), we can write Android apps using any language that can be compiled to generate bytecode, which JVM is able to understand.
There are a lot of options out there, such as Groovy, Scala, Clojure and, of course, Kotlin.

Advantages

What are the advantages of the language when compared to Java 7?
• It’s safer: Kotlin is null safe. We need to explicitly specify if an object can be null, and then check its nullity before using it.
• It’s functional: Kotlin is basically an object oriented language, not a pure functional language.
• It makes use of extension functions: This means we can extend any class with new features even if we don’t have access to the its source code.
• It’s highly interoperable: You can continue using most libraries and code written in Java.

Null Safety

Kotlin, as many other modern languages, is null safe because we need to ` ` explicitly specify if an object can be null by using the safe call operator (written ? )

// Artist can be null
var artist: Artist? = null
// Will print only if artist != null
artist?.print()
// Smart cast. We don't need to use safe call operator if we previously
// checked nullity
if (artist != null) {
artist.print()
}
// Only use it when we are sure it's not null. Will throw an exception otherwise.
artist!!.print()
// Use Elvis operator to give an alternative in case the object is null.
val name = artist?.name ?: "empty"

Extension functions

We can add new functions to any class. We could, for instance, add a new method to fragments to show a toast.

fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(getActivity(), message, duration).show()
}
///We can now do:
fragment.toast("Hello world!")

Functional support (Lambdas)

What if, instead of having to implement an anonymous class every time we need to implement a click listener.

view.setOnClickListener { toast(“Hello world!”) }

Android studio Setup — 2

Configure Gradle

Parent build Gradle:

buildscript {
ext.kotlin_version = '1.0.0'
ext.anko_version = '0.8.2'

dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

App build Gradle:

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.anko:anko-common:$anko_version"
}
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_versio\
n"
}
}

Anko is a library that uses the power of Kotlin to simplify some tasks with Android.

Convert MainActivity to Kotlin code

Open the file and select Code -> Convert Java File to Kotlin File .

Classes and Functions — 3

How to declare a class

class MainActivity {
}

Brackets are not required if the class doesn’t have any content:

class Person(name: String, surname: String)

Class inheritance

Classes are closed by default (final), so we can only extend a class if it’s explicitly declared as open or abstract.

open class Animal(name: String)
class Person(name: String, surname: String) : Animal(name)

we need to specify the parameters we’re using for the parent constructor. That’s the equivalent to super() call in Java.

Functions

Functions (our methods in Java) are declared just using the fun keyword:

fun onCreate(savedInstanceState: Bundle?) {
}

It you don’t specify a return value, it will return Unit , similar to void in Java, though this is really an object.

I’m not using semi-colons at the end of the sentences. While you can use them, semi-colons are not necessary and it’s a good practice not to use
them.

Constructor and functions parameters

fun toast(message: String, length: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, length).show()
}

The second parameter ( length ) specifies a default value. This means you can write the second value or not, which avoids the need of function overloading.

Named arguments can be used, which means you can write the name of the argument preceding the value to specify which one you want:

toast(message = “Hello”, length = Toast.LENGTH_SHORT)

Writing First Class — 4

Object instantiation: Object instantiation presents some differences from Java too. We omit the “ new ” word.

Default visibility is public: Unless some visibility modifier is applied, classes, functions or properties are public by default.

Variables and properties — 5

Basic types

There are no automatic conversions among numeric types. For instance, you cannot assign an Int to a Double variable. An explicit conversion must be done.

val i: Int = 7
val d: Double = i.toDouble()

Bitwise arithmetical operations are a bit different. In Android, we use bitwise or quite often for flags, so I’ll stick to “ and ” and “ or “ as an example:

// Java
int bitwiseOr = FLAG1 | FLAG2;
int bitwiseAnd = FLAG1 & FLAG2;
// Kotlin
val bitwiseOr = FLAG1 or FLAG2
val bitwiseAnd = FLAG1 and FLAG2

There are many other bitwise operations, such as shl , shs , ushr , xor or inv .

Literals can give information about its type. It’s not a requirement, but a common practice in Kotlin is to omit variable types.

val i = 12 // An Int
val iHex = 0x0f // An Int from hexadecimal literal
val l = 3L // A Long
val d = 3.5 // A Double
val f = 3.5F // A Float

A String can be accessed as an array and can be iterated:

val s = "Example"
val c = s[2] // This is the Char 'a'

Variables

Variables in Kotlin can be easily defined as mutable ( var ) or immutable ( val ). The idea is very similar to using final in Java variables.

If we want to make use of immutability. The key concept: just use val as much as possible.

However, a type needs to be specified if we want to use a more generic type:

val a: Any = 23
val c: Context = activity

Properties

This is the code required in Java to safely access and modify a field:

public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

In Kotlin, only a property is required:

public class Person {
var name: String = ""
}

If the property needs access to its own value in custom getter and setter (as in this case), it requires the creation of a backing field. It can be accessed by using field , a reserved word, and will be automatically created by the compiler. The backing field can only be used inside property accessors.

Move to part — 2

--

--

Md Ali Hossain

Senior Android Engineer @Delivery Hero | Android developer | Kotlin lover | Flutter explorer | Problem Solver