Learn Kotlin gist for android developers part- 1

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

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 {
}
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)

Functions

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

fun onCreate(savedInstanceState: Bundle?) {
}

Constructor and functions parameters

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

Writing First Class — 4

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()
// Java
int bitwiseOr = FLAG1 | FLAG2;
int bitwiseAnd = FLAG1 & FLAG2;
// Kotlin
val bitwiseOr = FLAG1 or FLAG2
val bitwiseAnd = FLAG1 and FLAG2
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
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.

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;
}
}
public class Person {
var name: String = ""
}

--

--

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

Md Ali Hossain

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