Kotlin is a relatively young language from the Russian company JetBrains. It appeared in 2011. At the Google I/O 2017 conference, the Android development team announced that Kotlin has received official support for the development of Android applications.

Like Java, C, and C++, Kotlin is a statically typed language. It supports both object-oriented and procedural programming. By analogy with the above-mentioned languages, the main code of the Kotlin program is written in the function , to which an array of command line arguments is passed:

main

 


package hello

fun main(args: Array < String > ) {
   val scope = "world"
   println("Hello, $scope!") 

Here are the main features and benefits of Kotlin:

  • Compiled to JVM bytecode or JavaScript.
  • programs can use all existing Java frameworks and libraries. Kotlin can be integrated with Maven, Gradle and other build systems;
  • the language is very easy to learn;
  • the source code is open;
  • IntelliJ automatically converts Java code to Kotlin and vice versa.
  • null-secure language — annoying NullPointerException remained in Java. Here's an example of the code:
    val name: String = null // attempting to assign null will not compile.
    fun getName() : String = null // trying to return null will not compile.
  • easy-to-read syntax will not be a problem with code review.

Let's analyze some of them in more detail.

Null security

When you try to assign or return null, the code is not compiled. However, the language does have support for Nullable types. You can specify such a variable or function by attaching to the type name:?

val name: String? = null 
fun getName() : String? = null 
/* wrong */
val name: String? = null val len = name.length /* right */
val name: String? = null val len = name?.length

Flexibility and simplicity of syntax

Simple functions and structures can be declared with a single line. Getters and setters are set behind the scenes for interoperability with Java code. Adding a data-annotation to a class activates the automatic generation of various templates.

Consider the following example:

/* Java program */
public class Address { private String street; private int streetNumber; private String postCode; private String city; private Country country; public Address(String street, int streetNumber, String postCode, String city, Country country) { this.street = street; this.streetNumber = streetNumber; this.postCode = postCode; this.city = city; this.country = country; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address address = (Address) o; if (streetNumber != address.streetNumber) return false; if (!street.equals(address.street)) return false; if (!postCode.equals(address.postCode)) return false; if (!city.equals(address.city)) return false; return country == address.country; } @Override public int hashCode() { int result = street.hashCode(); result = 31 * result + streetNumber; result = 31 * result + postCode.hashCode(); result = 31 * result + city.hashCode(); result = 31 * result + (country != null ? country.hashCode() : 0); return result; } @Override public String toString() { return "Address{" + "street='" + street + '\'' + ", streetNumber=" + streetNumber + ", postCode='" + postCode + '\'' + ", city='" + city + '\'' + ", country=" + country + '}'; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public int getStreetNumber() { return streetNumber; } public void setStreetNumber(int streetNumber) { this.streetNumber = streetNumber; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } }
/* Same Kotlin program */
data class Address(var street:String, var streetNumber:Int, var postCode:String, var city:String, var country:Country)

Differences from Java

Null security

As mentioned earlier, Kotlin does not allow a NullPointerException to occur by throwing a compilation error.

Data Classes

Kotlin has special classes designed specifically for data storage. They generate different templates: , , , getters and setters, etc. Compare Java code:equals()hashCode()toString()

class Book {
   private String title;
   private Author author;
   public String getTitle() {
       return title;
   }
   public void setTitle(String title) {
       this.title = title;
   }
   public Author getAuthor() {
       return author;
   }
   public void setAuthor(Author author) {
       this.author = author;
   }
}

And on Kotlin:

/* Kotlin */
data class Book(var title:String,var author:Author)

Easily create copies of data classes using the :copy()

val book = Book("Kotlin", "JetBrains")
val copy = book.copy()

Extensibility Features

Kotlin allows you to extend the functionality of existing classes without resorting to inheritance. This is done using extension functions. To declare such a function, you need to attach a prefix to its name in the form of an extensible type. This is how you can add a function to :swapMutableList

fun MutableList<Int>.swap(index1:Int,index2:Int){
   val tmp=this[index1]
   this[index1]=this[index2]
   this[index2]=tmp
}

The this keyword inside an extension function refers to the consumer object that is passed before the point. Now we can apply the swap function to any list being modified:

val abc = mutableListOf(1, 2, 3)
abc.swap(0, 2)

Smart type conversions

The Kotlin compiler is very smart when it comes to type conversions. In most cases, you don't need to explicitly specify casting operators, because a language has an operator that does all the work for you:is

fun demo(x:Any) {
   if(x is String) {
      print(x.length)  // x автоматически приводится к типу String
   }
}

Type Inference

In Kotlin, it is not necessary to explicitly specify the type of a variable:

/* неявное определение */
fun main(args: Array<String>) {
   val text = 10
   println(text)
}

/* явное определение */
fun main(args: Array<String>) {
   val text: Int = 10
   println(text)
}

Functional programming

It is important to note that Kotlin is sharpened for functional programming. It provides many useful features, such as higher-order functions, lambda expressions, operator overloading, and lazy calculation of Boolean expressions. Here's an example of working with collections:

fun main(args: Array<String>) {
   val numbers = arrayListOf(15, -5, 11, -39)
   val nonNegativeNumbers = numbers.filter { it >= 0 }
   println(nonNegativeNumbers)
}
// Вывод: 15, 11

Higher-order functions are functions that take other functions as arguments and return functions. Consider the following example:

fun alphaNum(func: () -> Unit) {}

In it, this is the name of the argument, and this is the type of function. We say that it will be a function that does not accept arguments and returns nothing.func( ) -> Unitfunc

Lambda expressions, or anonymous functions, are functions that are not declared, but passed as expressions. Here's an example:

val sum: (Int, Int) -> Int = { x, y -> x + y }

We declare a variable , which takes two numbers, adds them up, and takes the sum value reduced to an integer. A simple one is enough to call.sumsum(2,2)

Java and Kotlin speed comparison

The first build of Kotlin code takes about 15-20% more time than a similar process in Java. However, Kotlin's incremental build is even slightly faster than Java's. Thus, the languages are approximately equal in compilation speed.

The Future of Kotlin

Kotlin is the next stage in the development of Java, with which it is fully compatible. This makes it a great tool for mobile and enterprise applications. And since Kotlin is now the official language of Android, you can not be afraid that after studying it, you will be left without a job.

In learning this language, you will be helped by a series of articles describing the process of creating a simple mobile application Keddit - a client for the popular reddit resource. All its parts for your convenience we have listed in the list below.

You'll need the following libraries:

  • Retrofit 2.0;
  • RxJava;
  • Picasso;
  • RecyclerView;
  • Kotlin extensions for Android;
  • Dagger 2.

All sources are available on GitHub. The series consists of the following parts:

If you prefer the video format, pay attention to the Russian-language video course on Kotlin.

Advantages

 

Kotlin is fully compatible with Java. This means that you can call functions declared in Java code directly from Kotlin code and vice versa, including using a large number of existing Java libraries.

In the kotlin program, you can use any Java frameworks. And Kotlin can be integrated with build systems such as Maven and Gradle.

Brevity. This is one of the main factors due to which more and more developers choose Kotlin.

Kotlin is null-safe. The creators of the language did everything to make NullPointerException a thing of the past. These are some of the most common exceptions, and they are almost impossible to track at compile time. This means that errors will occur only while the program is running.

A nullPointerException occurs when the variable that the program is trying to access is null. Therefore, in Kotlin, the default variable cannot be set to null unless explicitly specified. For example, the code below will not compile because there is no "?" after the variable type:

val name: String = null

In order for the name variable to be null, you need to specify this explicitly using the "?":

val name: String? = null

In the code below, the hashCode() function will not be called because the variable name is null when the function is called.

val name: String? = null
name?. hashCode()

Extensibility functions. Kotlin allows you to change the functionality of existing classes without class inheritance. This is a convenient tool that allows you to increase the readability of the code. To declare the extension of a function, you must add a prefix to its name in the form of an extensible type, for example:

fun String.addGreeting(): String{
return “Hello “ + this

}

Then calling such a function might look like this:

val name = “SkillFactory”
println(name.addGreeting())

Kotlin is open source. Kotlin code is open to programmers, and its implementation in the project is also free. Open source makes it easy to find problems. Kotlin developers listen to third-party developers and make changes proposed by the community.

Easy to learn. Many note that Kotlin is easy to learn and suitable as a programming language for beginners.

Disadvantages

Compilation speed. Often there are problems with the speed of code compilation. This is not a constant phenomenon, sometimes compilation is even faster than Java code, but such moments frustrate developers.

A small number of tutorials. The community of developers in the Kotlin programming language is still young and there are not so many articles on development, especially for "dummies". Here are some useful materials in Russian language for beginners.

  • Kotlin video tutorials for beginners from Devcolibri.
  • Kotlin Manual.

A small number of libraries on Kotlin. The reason is the same – the language is still quite young. But this disadvantage is compensated by full compatibility with Java - you can use a large number of existing Java libraries.