Getting Started With Kotlin for Android Development

Getting Started With Kotlin for Android Development
by

If you are a mobile developer, you are probably using the Java language for building Android apps. But did you know that new languages that might challenge Java’s in the Android are popping up all over the place? One of them is Kotlin. This year, Google acknowledged Kotlin and made it the second official language of Android.Since May 2017, Kotlin tools are included with Android Studio 3.0 by default. Kotlin first appeared in 2011, as a new language for Java Virtual Machine from a team of Saint-Peterburg programmers called JetBrains. JetBrains is the company who also have built IntelliJ IDEA software.

What is Kotlin?

Kotlin is a statically typed programming language developed by JetBrains, which is designed to run on the Java Virtual Machine (JVM).  It is compatible with both object-oriented (OO) and functional programming (FP) language

While it is not syntax-compatible with java, Kotlin is designed to interoperate with Java code and is reliant on Java code from the existing Java Class Library.

However, Kotlin is an enhancement of Java, rather than a completely new language, so many of the skills that you have acquired in your Java career should still be applicable to your Kotlin projects.

Benefits of Kotlin

  • Easy to Set Up with Android studio
  • Most Versatile & Secure Language
  • Automatic type casting
  • Make android development much easier
  • Interoperable With Java
  • Language and environment fully tested before release
  • Can create functions inside class
  • Everything in Kotlin is closed by default
  • No need to use findViewById
  • Saves lengthy line of code

Why Kotlin Use For Android App Development Over Java?

Kotlin on Android is the future while Java is the past. Kotlin aims to fill the gap in a missing modern language for the Android platform. Kotlin has the advantage over Java as a programming language because it can support various features that currently are not supported by Java.

First: What’s the “Problem” With Java?

  • Null references are controlled by the type system: One of the most common exception is null pointer exception, which is eliminated in Kotlin using!! Operator.
  • No raw types: Kotlin is designed with Java Interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java rather smoothly as well.
  • Arrays in Kotlin are invariant Kotlin does not allow us to assign an Array<String>to an Array<Any>, which prevents a possible runtime failure (but you can use Array<out Any>.Kotlin also has specialized classes to represent arrays of primitive types without boxing overhead: ByteArray, ShortArray, IntArray and so on. These classes have no inheritance relation to the Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function:
  • Kotlin has proper function types, as opposed to Java’s SAM-conversions: Kotlin uses a family of function types like (Int) -> Stringfor declarations that deal with functions: val onClick: () -> Unit
  • Kotlin does not have checked exceptions : Checked exceptions are those where the compiler forces the caller of a function to catch or (re-throw) an exception. These are often unnecessary and cause empty catch blocks. Non-existent checked exceptions are an annoyance for developers because they’re forced to weed through code to identify a possible exception that never actually occurred. As a solution, Kotlin removed them entirely, which again minimizes verbosity and improves type-safety.

Talk to our Kotlin expert
to put your ideas into execution

Hire a Kotlin Developer

Kotlin has many features and tools that Java lacks. But Kotlin respects some fundamental principles. It has introduced new function that are not supported by java. Let me explain below.

  • Extension functions: It is used to extend a class with new functionality. Basically, an extension function is a member function of a class that is defined outside the class.
    For example, you need to use a method to the String classthat returns a new string with first and last character removed; this method is not already available in String You can use extension function to accomplish this task.
fun String.removeFirstLastChar(): String =  this.substring(1, this.length - 1)

fun main(args: Array<String>) {
val myString= "Hello Everyone"   
val result = myString.removeFirstLastChar()   
println("First character is: $result") } Output : First character is: ello Everyone
  • Null-safety : Kotlin compiler by default doesn’t allow any types to have a value of null at compile-time.
  • Smart casts : Suppose we have a function: fun someMethod(obj: Any?) {}
    Here the variable objis both optional and derived from the Kotlin root class (Any). This means that obj could be basically any kind of class if it isn’t null.
  • String templates : They are represented by the type String. Strings are immutable, can concatenate string using + operator.
  • Properties : Classes in Kotlin have properties. These can be declared as mutable, using the varkeyword or read-only using the val
  • Primary constructors : The classes in kotlin has primary and secondary constructor
class Person constructor(firstName: String) { ... }  = > Primary constructor

class Person { => Secondary constuctor
constructor(parent: Person) {
parent.children.add(this)   
} }
  • Declaration-site variance: It supports “delegation”design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. The following example demonstrates how this happens in Kotlin.
interface Base { 
fun printMe() //abstract method } class BaseImpl(val x: Int) : Base {
override fun printMe() { println(x) }  //implementation of the method } class Derived(b: Base) : Base by b  // delegating the public method on the object b fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).printMe() // prints 10 :: accessing the printMe() method }
  • Lambda expressions: To print hello world in lambda expression use below code :
Basic Syntax

val printHelloWorld = {
println("Hello, world!") } printHelloWorld() // or printHelloWorld.invoke()

Set-Up Kotlin with Android Studio

Follow our setup instructions to create a new Kotlin project with Android studio. To follow these steps you can create simple Kotlin application for Android using Android Studio.

Let’s get started!

Step – 1 Install the Kotlin Plugin for your Android Studio.

Android Studio → Preferences →Plugins → Browse Repository → type “Kotlin” in search box → install

Step – 2 Add Kotlin classpath to project Build.Gradle

buildscript {
ext.kotlin_version = "1.2.70"
ext.supportLibVersion = "25.3.0"
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
} }

Step 3: Add Kotlin library and apply Kotlin Plugins in your module Build.gradle.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
// ... various gradle setup } dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile "com.android.support:appcompat-v7:$supportLibVersion"
compile "com.android.support:recyclerview-v7:$supportLibVersion"
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" }

Step 4: Ready to go

Now Kotlin is setup for your app development and you can start writing Kotlin code (in .kt extension). Another way is convert your Java file to Kotlin, using Shift-Alt-Cmd-K or Shift-Shift + search Convert Java File to Kotlin File.

Summary:

As a new language, Kotlin is a safe and expressive language as compared to java. It is getting enhanced day-by-day and we can conclude by saying that it is evolving as the favorite language for an Android developer. It will help make your life as an Android developer a lot easier.  Kotlin can take the Android app development a step further with its ease of understanding, implication, and the trouble free security from exceptions. It is believed that Kotlin will soon win the eyeballs and replace our traditional programming language on a large scale. If you have any questions about Kotlin, drop an email to us, and we will get in touch with you.


Looking to hire dedicated Kotlin developers? Let us help!

Contact us and let’s talk about your business

HIRE KOTLIN DEVELOPERS