Kotlin is a language by JetBrains, the company behind IntelliJ IDEA, which Android Studio is based on, and other developer tools. Kotlin is purposely built for large scale software projects to improve upon Java with a focus on readability, correctness, and developer productivity.
The language was created in response to limitations in Java which were hindering development of JetBrains' software products and after an evaluation of all other JVM languages proved unsuitable. Since the goal of Kotlin was for use in improving their products, it focuses very strongly on interop with Java code and the Java standard library.
Defining local variables
Assign-once (read-only) local variable:
Mutable variable:
Function having two Int parameters with Int return type:
Function with an expression body and inferred return type:
Function returning no meaningful value:
Unit return type can be omitted:
Iterating over a collection:
Checking if a collection contains an object using in operator:
Using lambda expressions to filter and map collections:
Dealing with null
To be able to write and compile Kotlin code in your Android application you need to do the following:
Preferences (OSX)
or Settings (Windows/Linux)
-> Plugins
-> Browse Repositories
type Kotlin
to find the Kotlin plugin. Click Install
and follow the instructions.Click on Tools
-> Kotlin
-> Configure Kotlin in Project
Select Android with Gradle
ChooseAll Modules
-> Select the Kotlin compiler and the runtime version
you want from the dropdown and click OK
.
Your build.gradle
file will look like this:
You can start by converting your existing Java File to Kotlin file. Open your Java File -> Click on Code
menu item -> select Convert Java File to Kotlin File
.
Your converted file should look like this:
Starting from Kotlin version 1.0.2
, action to create new activity in Kotlin has been added. To create new Android Kotlin activity, Go to File
-> New
->Kotlin Activity
.