From Bauman National Library
This page was last modified on 1 June 2016, at 17:09.
Designed by JetBrains
First appeared 2016
Preview release 1.0 RC / 04.02.2016
Typing discipline static
Platform Java Virtual Machine
OS any supporting JVM
Website http://kotlinlang.org/
Influenced by
Java, Scala, Groovy, Gosu, Ceylon, C#

Kotlin — statically typified programming language working a top JVM and developed by the JetBrains company. It is compiled also in JavaScript.

Authors set as the purpose to create language more laconic and tipobezopasny, than Java, and simpler, than Scala. A consequence of simplicity compared with Scala also became faster compilation and better language support in the IDE.

Language is developed since 2010, is publicly presented in July, 2011. The initial code was open in February, 2012. In February, it was released milestone 1, which includes a plugin for IDEA. In June — milestone 2 with support of Android. In December 2012 came milestone 4, including, in particular, support for Java 7. As of November, 2015 the main opportunities of language are stabilized, release of version 1.0 prepares.Prerequisites


To create a class in Kotlin, you have to use the class keyword. For example, here’s how you create an empty class called Person:

class Person {

Adding Properties

A class usually has properties and member functions (also called methods). Let’s add two properties to the Person class, name of type String and age of type Int.

var name: String = ""
var age: Int = 0

As you can see, the syntax for creating variables is slightly different from that of Java. To create a variable in Kotlin, you must use the var keyword. However, if you want your variable to be a read-only/assign-once variable, use the val keyword instead.

For the sake of null safety, Kotlin also makes a distinction between variables that can be null and variables that can never be null. In our previous example, both the variables name and age can never be null. If they are null, the compiler will raise an error.

To create a variable that can hold null, you need to add a ? after the variable’s type. For example:

var college: String? = null

Now that we have a class, creating an instance of it is easy. For creation of a copy of a class the keyword of new isn't specified. After the copy was created, you can get access to its property the same as in Java:

var jake = Person()
jake.name = "Jake Hill"
jake.age = 24
jake.college = "Stephen's College"

Using Constructors

Kotlin’s syntax to create such a constructor is very compact:

class Person(var name: String, var age: Int, var college: String?) {

To add more constructors to your class, known as secondary constructors, you should use the constructor keyword. Secondary constructors should delegate to the primary constructor using the this keyword. Let’s add a secondary constructor to our class that initializes the value of a property named email:

class Person(var name: String, var age: Int, var college: String?) {
   var email: String = ""
   constructor(name:String, age:Int, college: String?, email: String) : this(name, age, college) {
      this.email = email

To create an instance using the secondary constructor, you write something like this:

var jake = Person("Jake Hill", 24, "Stephen's College", "jake.hill@example.com")

Adding Member Functions

In Kotlin, functions are created using the fun keyword. Let’s add a simple member function named isEligibleToVote that returns a Boolean value:

fun isEligibleToVote(): Boolean {
   // If age is greater or equal to 18
   // return true 
   return age >= 18

Note that the return value’s type is indicated at the end of the function header. You can call this method the same way you would in Java:


Creating Extensions

Kotlin lets you extend a class by adding additional functions to it without modifying its original definition. Such functions are known as extensions. The names of these functions should be preceded by the names of the classes they extend.

For example, to add an extension called isTeenagerto the Person class, you write the following code outside the class:

fun Person.isTeenager(): Boolean {
   // If age falls in the range
   // 13-19 return true 
   return age in 13..19

This feature is especially useful when you want to extend classes that do not belong to your project’s code base. For example, the following code snippet adds an extension containsSpacesto the String class:

fun String.containsSpaces(): Boolean {
   return this.indexOf(" ")!=-1

Creating Derived Classes

It’s important to keep the following in mind when creating a derived class:

  • You must use a : (instead of Java’s extends keyword).
  • The header of the base class should have the open annotation.
  • If your base class has a constructor that takes parameters, your derived class should initialize those parameters in the header itself.

Let’s create a class named Employeethat derives from Person:

open class Person(var name: String, var age: Int, var college: String?) {
class Employee(name: String, age: Int, college: String?, var company: String) : Person(name, age, college) {

Overriding Member Functions

In Kotlin, you have to explicitly state that a member function can be overridden by using the open annotation in the method’s header in the base class. In the derived class, open functions can be overriden using the override annotation.

For example, to override the isEligibleToVote method, you add the following code snippet to the Employee class:

override fun isEligibleToVote(): Boolean {
   // Always return true
   return true

Creating Static Methods

Kotlin does not allow you to create static methods. However, it does allow you to create package level functions that do not belong to any class.

The main method is perhaps the best known static method. If you want to add the main method to a package named com.tutsplus.code.tutorial, then your code would look like this:

package com.tutsplus.code.tutorial

fun main(args:Array<String>) {


In the previous examples simple functions were described. Syntax for their creation was it is very similar to Java. Kotlin, however, allows to make much more with functions.

Creating Single Expression Functions

If a function returns the value of a single expression, then you can use the = operator after the function header followed by the expression to define the function.

For example, to add a method to the Person class that returns true if the person is an octogenarian, you would write:

fun isOctogenarian(): Boolean = age in 80 .. 89

As you can see, this shorthand syntax is more compact and readable.

Higher Order Functions and Lambda Expressions

Higher order functions are functions that can return functions or accept functions as parameters. A lambda expression, on the other hand, is just a function that has no name. Usually, lambda expressions and higher order functions are used together.

Consider the following example that demonstrates the syntax of a lambda expression:

{x, y -> x+y}

This is a simple lambda expression that takes two parameters, x and y, and returns their sum. As you might have guessed, the parameters of the function are listed before the -> operator and the body of the function starts after the -> operator. This lambda expression can be assigned to a variable and used as follows:

val sumLambda: (Int, Int) -> Int = {x,y -> x+y}
val actualSum = sumLambda(3,4)

Note that the type of the variable that holds the lambda expression specifies the types of its parameters and its return value.

Creating a higher order function that can accept the above lambda expression as a parameter is just as easy. For example, to create a function that doubles the result of the lambda expression, you would write:

fun doubleTheResult(x:Int, y:Int, f:(Int, Int)->Int): Int {
   return f(x,y) * 2

This function can be caused as follows:

val result1 = doubleTheResult(3, 4, sumLambda)

Alternatively, you can pass the lambda expression directly to the higher order function:

val result2 = doubleTheResult(3, 4, {x,y -> x+y})

Lambda expressions are often used with arrays. For example, consider the following array of Int values:

val numbers:Array<Int> = arrayOf(1, 2, 3, 4, 5)

If you want to square the value of each item in the array, you can use the map function along with a lambda expression as follows:

val squaredNumbers = numbers.map({x -> x * x})
// Result will be a new array that contains
// 1, 4, 9, 16, 25


Range expressions are used very frequently in Kotlin. You already used them while creating the isTeenager and isOctogenarian methods.

To create a range, all you need is the .. operator.

val r1 = 1..5
// This range contains the number 1, 2, 3, 4, 5

To create a range in descending order, use the downTo function instead.

val r2 = 5 downTo 1 
// This range contains the number 5, 4, 3, 2, 1

If you don’t want the step to be 1, you can specify a custom value using the step function.

val r3 = 5 downTo 1 step 2
// This range contains the number 5, 3, 1

Conditional Constructs


In Kotlin, if is an expression that returns different values depending on whether the condition has been satisfied. The following example illustrates how this works.

var age = 20
val isEligibleToVote = if(age > 18) "Yes" else "No"
// isEligibleToVote will now be set to "Yes"


The when expression is equivalent to Java’s switch. However, it is a lot more versatile. For instance, consider the following example.

val age = 17

val typeOfPerson = when(age){
   0 -> "New born"
   in 1..12 -> "Child"
   in 13..19 -> "Teenager"
   else -> "Adult"
// typeOfPerson will now be set to "Teenager"

Looping Constructs


In Kotlin, you can use the for..in loop to loop through arrays, collections, and anything else that provides an iterator. Its syntax is almost identical to that of Java, except for the use of the in operator instead of Java’s : operator. The following example shows you how to loop through an array of String objects.

val names = arrayOf("Jake", "Jill", "Ashley", "Bill")
for (name in names) {

With the help of range expressions, you can make this loop behave like a traditional, C-style, for loop.

for (i in 0..9) {
// Behaves exactly like
for(int i=0;i<10;i++)

while and do..while

The syntax of while<.code> and <code>do..while<.code> loops in Kotlin is identical to the syntax used in Java. For example, the following Kotlin code loops over an array of String objects using a <code>while loop:

val names = arrayOf("Jake", "Jill", "Ashley", "Bill")
var i = names.size()
while(i>0) {

String Templates

Kotlin lets you embed variables and expressions in strings by wrapping them in a pair of curly braces, prefixed by a $ symbol. For example:

val name = "Bob"
println("My name is ${name}") // Prints "My name is Bob"

val a = 10
val b = 20
println("The sum is ${a+b}") // Prints "The sum is 30"