Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using the Kotlin Language in building Android Apps

Author: idarwin
Published? false
FormatLanguage: AsciiDoc

Problem:

You've heard that Kotlin requires less "typing" than Java and want to try it out.

Solution:

Using Android Studio, create a New Project and ensure that you check the "Include Kotlin Support" box (see Fig 1). Click through the remaining screens to create the project. Behold: your main activity class is written in Kotlin instead of Java!

Discussion:

Kotlin is one of several newer programming languages that simplify Java. Kotlin has the advantage of compiling directly to JVM bytecode, so that anything which can be done in Java, can be done (probably more easily) in Kotlin. Here, for example, is most of the main code from a basic "Hello World" Android app generated by Android Studio's New Project wizard:

package com.darwinsys.myapplication

import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar)

fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } }

override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } .... }

Since you've read this far in the book we'll assume you know Java and Android well enough to understand most of this code. Note the following:
  • Lots of types and declarations are inferred;
  • ":" instead of `extends`
  • You don't have to declare the return type of functions (or even whether they're void) when overriding, as that information is inferred by the compiler. Just use the override keyword (not an added-on Annotation as in Java), and the `fun` keyword to define a function, returning a value if needed.
  • Where does `fab` come from? It is only declared in the layout XML file, yet the Kotlin code is able to access it.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    ...
/>

That's pretty neat, and symptomatic of the kinds of things that Kotlin and its Android Studio can do to make your life easier.

See Also:

For more information, check out some or all of the following: