Learn Kotlin gist for android developers part- 1

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

Advantages

Null Safety

// 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

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)

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

Android studio Setup — 2

Configure 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

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

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

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

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

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

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Md Ali Hossain

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