Getting started with Kotlin

Kotlin
Kotlin

Kotlin is expressive, concise, extensible, powerful, and a joy to read and write. It has wonderful safety features in terms of nullability and immutability, which aligns with our investments to make Android apps healthy and performant by default.

Introduction to basic Kotlin programming

All Kotlin programs start at the main function. Here is an example of a simple Kotlin “Hello World” program:

package my.program

fun main(args: Array<String>) {
    println("Hello, world!")
}

Place the above code into a file named Main.kt (this filename is entirely arbitrary)

When targeting the JVM, the function will be compiled as a static method in a class with a name derived from the filename. In the above example, the main class to run would be my.program.MainKt

To change the name of the class that contains top-level functions for a particular file, place the following annotation at the top of the file above the package statement:

@file:JvmName("MyApp")

In this example, the main class to run would now be my.program.MyApp

Similar to using an Object Declaration, you can define the main function of a Kotlin program using a Companion Object of a class.

package my.program

class App {
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            println("Hello World")
        }
    }
}

The class name that you will run is the name of your class, in this case, is my.program.App

The advantage to this method over a top-level function is that the class name to run is more self-evident, and any other functions you add are scoped into the class App This is similar to the Object Declarationexample, other than you are in control of instantiating any classes to do further work.

A slight variation that instantiates the class to do the actual “hello”:

class App {
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            App().run()
        }
    }

    fun run() {
        println("Hello World")
    }
}

Resources to Learn Kotlin

The Kotlin Website

The official website for the project is a very good place to start your Kotlin education.

Design Patterns implemented in Kotlin

Dariusz Baciński has created a useful GitHub repo containing common design patterns implemented in Kotlin. There are similar projects written in several languages including JavaSwiftJavaScript, and PHP, so if you are coming from one of these programming backgrounds you can use them as a reference point.

Android Official Developer Site

Kotlin is fully supported in Android Studio 3.0 (get the canary version here), so it’s easy to create new projects with Kotlin files, add Kotlin files to your existing project, and convert Java language code to Kotlin.

LEAVE A REPLY