Java features

What is Kotlin? The Java alternative explained

Kotlin offers big advantages over Java for JVM and Android development, and plays nicely with Java in the same projects. Why not give it a try?

1 2 Page 2
Page 2 of 2
import java.util.Calendar  

fun calendarDemo() {
     val calendar = Calendar.getInstance()
     if (calendar.firstDayOfWeek == Calendar.SUNDAY) {  // call getFirstDayOfWeek()
         calendar.firstDayOfWeek = Calendar.MONDAY      // call setFirstDayOfWeek()
     if (!calendar.isLenient) {                       // call isLenient()
         calendar.isLenient = true                  // call setLenient()

This scheme breaks down for the case of Java set-only properties, which are not yet supported in Kotlin. If a Java class has only a setter, it will not be visible as a property in Kotlin.

Kotlin’s interoperability with Java extends to Java tools. Kotlin doesn’t have its own editors or IDEs; it has plug-ins for the popular Java editors and IDEs, including IntelliJ IDEA, Android Studio, and Eclipse. Kotlin doesn’t have its own build system; it uses Gradle, Maven, and Ant.

Kotlin interoperability with JavaScript

You can use Kotlin to write code for browsers and Node.js. With this target, Kotlin is transpiled to JavaScript ES5.1 instead of being compiled to JVM byte code.

Because JavaScript is a dynamic language, Kotlin for JavaScript adds a dynamic type not available in Kotlin for the JVM:

val dyn: dynamic = ...

The Kotlin type checker ignores dynamic types and lets JavaScript deal with them at runtime. Expressions using values of dynamic type are translated to JavaScript as written. Again, Kotlin basically punts and lets JavaScript interpret the expressions at runtime.

You can call JavaScript from Kotlin two ways: using dynamic types or using strongly typed Kotlin headers for JavaScript libraries. To access well-known, third-party JavaScript frameworks with a strongly typed API, you can convert TypeScript definitions from the DefinitelyTyped type definitions repository to Kotlin using the ts2kt tool.

You can inline JavaScript code as text into your Kotlin code using the js(“…”) function. You can mark package declarations in Kotlin code as pure JavaScript with the external modifier. You can call Kotlin code from JavaScript, but you need to use fully qualified names.

Overall, Kotlin offers a number of advantages over Java for code to be run on the JVM, and can also generate JavaScript and native code. Compared to Java, Kotlin is safer, more concise, and more explicit. It supports functional programming in addition to object-oriented programming, offers a bunch of useful features (extension functions, builders, coroutines, lambdas, etc.), and provides null safety through nullable and non-nullable types. Best of all, if you already know Java, you’ll be productive in Kotlin in no time.

1 2 Page 2
Page 2 of 2