Introduction to Kotlin for Android 

  • By : Subba Raju
  • Date :28-06-2018

In the Android world, I'm sure there is nobody who has not heard of Java. A powerful programming language that can build applications that run on almost any operating system on any hardware. However, over the years, a number of new programming languages have been introduced to also run on the Java virtual machine. One such language, which is a part of what Google is doing, to make Android app development "better" is Kotlin. Google announced its widespread support for Kotlin at Google I/O 2017.

Sure we know that Kotlin is for app developers and that they love it! But why do they love it? What makes Google reinforce that how important Kotlin is for app development again in 2018? What exactly is it?

A statically typed programming language that runs on JVM, Kotlin is a programming and development language from JetBrains. Kotlin is modern, expressive, safe and a powerful language which can be interoperable with our existing Android languages. Some other features include:

1. Kotlin is fully supported by Android Studio 3.0 and higher.

2. Kotlin is a JVM based language created by “JetBrains” , Team behind “Intellij”.

3. Intellij is base for Android Studio.

4. Kotlin is an “Object Oriented Language”

    Why Kotlin?

    Lightweight :

    Kotlin library is quite small when compared to others. This is important because Android method limits involving Proguard and Multidexing is always a problem to solve.All these Solutions will add complexities that can consume time while debugging.Kotlin adds less than 7000 Methods.

    Highly Interoperable :

    Kotlin works well with java libraries. Kotlin team wants to continue developing current projects which are written in java without having to rewrite the whole code. So Kotlin is extremely Interoperable language.

    Integrated with Android Studio :

    Kotlin is integrated with Android Studio and Gradle. It's easy to install Kotlin as it requires one plugin for the IDE and one for Gradle. It won’t be difficult to start an Android project using Kotlin.

    No More NullPointerExceptions :

    NullPointerException is one the most common cause of application crash in Android. To fix this exception and to protect your code, using null check every single time is a time consuming task. But in Kotlin this is an exception as null safety is already integrated.

    Performance :

    Kotlin application runs as fast as it would run on Java. With Kotlin support for inline functions, using “lambda” the applications often runs even faster.

    In Android Studio 3.0, you can choose to create the activity in Kotlin. The easiest way to start using kotlin is to convert Java to Kotlin automatically. You can write in Java, then copy-paste java code to kotlin file and it will suggest the conversion.

    Another easy Method to convert Java file to Kotlin:

    Android Studio Menu >> Code >> Convert Java File to Kotlin File

    The conversion will be of this type:

    Java:

    public class MainActivity extends AppCompatActivity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
      }
    }

    Kotlin:

    class MainActivity : AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity)
      }
    }

    After configuring Kotlin, update the build.gradle file for the application and implement the below shown:

    Drupal Module

     

    Drupal Module

    Finally, sync the project. You can click on 'Sync Now'. This works exactly same as in Java. You can make a release of the application and Sign it similarly to what we do for an Android application in Java.

    Finally Kotlin compiler produces “byte-code” , with no difference what so ever in terms of look and feel of the application in Android.

    Now, let us know a bit more about Kotlin Syntax

    • Package Defining:
      package  com.example
      Import java.util.* 

    • Defining Variables:
      Int:
      		Val  a: Int = 3 // Immediate assignment
      		Val  b = 2      // “Int” type is Inferred
      		Val  c : Int    // Type Required when no initializer is provided
      		C = 3          // Deferred assignment
          
      

    • String:
    val firstName: String = "Raj"
    	val lastName = "xyz"  // still compile
    	
    	val dateOfBirth = "24th April, 1990"
    dateOfBirth = "28th July, 2000" // cannot be changed
     
    var car = "Toyota Matrix"
    car = "Mercedes-Maybach" // can be changed
     

    Difference between “Val” and “Var”

    Val : Is a keyword that the former is immutable or read-only (its value cannot be changed)

    Var : Is a keyword which has its type inferred by the compiler, assigning another value of a different type won't work. In other words, the value of the variable can change, but its type cannot.

    var age = 12
    age = "12 years old" // Error: type mismatch
    
    val carName: String
    carName = "BMW Car" // will compile
    
    val carName = "Toyota", streetName = "Church street" // this won't compile
     
    
    // this will compile
    var carName = "Audi"
    var streetName = "Church street"
     

    Examples:

    fun main(args: Array<String>) {
        val i = 10
        println("i = $i")    // prints "i = 10"
    }
    
    val accountBalance = 200
    val bankMessage = "Your account balance is $accountBalance"
    // Your account balance is 200
    
    
     

    We refer to a variable by the use of a $ character in front of the variable name. Note that if the variable is not correct or doesn't exist, the code won't compile. You can call methods from an interpolated String directly; you have to add curly braces ${} to wrap it.

    val name = "Raj"
    val message = "The first letter in my name is ${name.first()}" 
    // The first letter in my name is R
    
    
     

    Defining Functions:

    fun sum(a: Int, b: Int): Int {
        		return a + b
    }
    
    
    fun main(args: Array<String>) {
        print("sum of 2 and 8 is ")
        println(sum(2, 8))
    }
    
    // sum of 2 and 8 is 10
    
     

    Function with an expression body and inferred return type:

    fun sum(a: Int, b: Int) = a + b
    
    fun main(args: Array<String>) {
        println("sum of 18 and 24 is ${sum(18, 24)}")
    }
    
    // sum of 18 and 24 is 42
    
    
    
     

    For Loop:

    fun main(args: Array<String>) {
        val items = listOf("apple", "banana", "Mango")
        for (item in items) {
            println(item)
        }
    }
    
    // apple
       banana
       Mango
    
    
     

    Using Collections:
     

    Iterating over a collection:
    		
    	fun main(args: Array<String>) {
        val items = listOf("apple", "banana", "mango")
        for (item in items) {
            println(item)
        }
    }
    
    Checking if a collection contains an object using “in” operator:
    
    fun main(args: Array<String>) {
        val items = setOf("apple", "banana", "mango")
        when {
            "orange" in items -> println("juicy")
            "apple" in items -> println("apple is fine")
        }
    }
    
    // apple is fine

    How To Create Instance Of Class:

    val customer = Customer()  // No New Keyword
    
     

    Constructors:

    A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header: it goes after the class name

    class Person constructor(firstName: String) {
    }
     

    Declaring Properties:

    Kotlin class have Properties. These can be declared as mutable, using the “var” keyword or Read-only using “val” keyword.

    For ex:

    class Address {
        	var name: String = “”
        	var street: String = “”
       	var city: String = “”
    }
    
     

    Interface :

    Interfaces in Kotlin are very similar to Java 8. They can contain declarations of abstract methods, as well as method implementations.

    An interface is defined using the keyword interface

    interface MyInterface {
        fun bar()
        fun foo() {
          // optional body
        }
    }
    
     

    Implementing Interfaces :

    class Child : MyInterface {
        override fun bar() {
            // body
        }
    }
     

    A class or object can implement one or more interfaces.

    Subscribe For Our Newsletter And Stay Updated

    Recent blogs

    top developer 2019 by Clutch
    CMS and e-commerce solutions have empowered Specbee to achieve the business objectives and deliver an awesome digital experience to...
    drupal 8.7
    How do you stay ahead of your competition? Easy - Be relevant. Address your audience’s pain points. Repeat. With the adoption of...
    Specbee Is All Set to Lead as the Top Drupal Development Company at GoodFirms
    CMS and e-commerce solutions have empowered Specbee to achieve the business objectives and deliver an awesome digital experience to...

    This website uses cookies to offer you an enhanced website experience. We collect information about how you interact with our website to provide personalized services to you. To find out more, see our Privacy Policy

    ×