Java as your Kotlin Study Buddy

Java as your Kotlin Study Buddy

Switching to a new primary language can be daunting. We know the ins and outs of the language we have been working with for years, and all the sudden we’re newbies again. While this is always a good exercise to put yourself in, and comes with lots of learning, there is also a bit of vulnerability. If your primary language has been Java, and you’re making the switch to Kotlin, you might be feeling a bit of this insecurity.

You’re in luck in this case. The knowledge you have of Java is in no way obsolete.

Kotlin is a language that runs on the Java Virtual Machine, with the same bytecode that is at the core of the Java we know. So there is a question you should ask:

How can we take advantage of this?

Because Kotlin compiles down to bytecode, we can decompile that bytecode into the equivalent Java. My favorite tool to do this is the Kotlin Bytecode Viewer right in Android Studio and IntelliJ IDEA. I like always having it right there in my IDE.

Other options include the ClassyShark Bytecode viewer, or Luyten. By using one of these latter options, you are able to view the decompiled Java from class files where you may not have the source. You can also compare results from different decompilers.

How can this be useful to you? Let’s say you come across this snippet of code:

val (phoneNumber, address) = friend.contactInfo

You know you have a friend object, and Friend has a contactInfo property. That property is a ContactInfo object that has a phone number and an address.

data class ContactInfo(val phoneNumber: String, val address: String)

What’s weird here is that we’re assigning the value of contactInfo to val (phoneNumber,eNumber, address).

This is not the Java I know. We can decompile the bytecode for this Kotlin to get a better sense of what exactly is going on.

ContactInfo var3 = friend.getContactInfo();
String phoneNumber = var3.component1();
String address = var3.component2();
var3 = null;

This Java clears a bit of this up.

What this is doing is getting the contact information from the friend object, then getting the phoneNumber and address from there. Not bad.

We can find out more about these numbered component methods by decompiling the ContactInfo data class.

public final class ContactInfo {
  @NotNull
  private final String phoneNumber;
  @NotNull
  private final String address;

  @NotNull
  public final String getPhoneNumber() {
     return this.phoneNumber;
  }

  @NotNull
  public final String getAddress() {
     return this.address;
  }

  public ContactInfo(@NotNull String phoneNumber, @NotNull String address) {
     Intrinsics.checkParameterIsNotNull(phoneNumber, "phoneNumber");
     Intrinsics.checkParameterIsNotNull(address, "address");
     super();
     this.phoneNumber = phoneNumber;
     this.address = address;
  }

  @NotNull
  public final String component1() {
     return this.phoneNumber;
  }

  @NotNull
  public final String component2() {
     return this.address;
  }

  @NotNull
  public final ContactInfo copy(@NotNull String phoneNumber, @NotNull String address) {
     Intrinsics.checkParameterIsNotNull(phoneNumber, "phoneNumber");
     Intrinsics.checkParameterIsNotNull(address, "address");
     return new ContactInfo(phoneNumber, address);
  }

  // $FF: synthetic method
  // $FF: bridge method
  @NotNull
  public static ContactInfo copy$default(ContactInfo var0, String var1, String var2, int var3, Object var4) {
     if((var3 & 1) != 0) {
        var1 = var0.phoneNumber;
     }

     if((var3 & 2) != 0) {
        var2 = var0.address;
     }

     return var0.copy(var1, var2);
  }

  public String toString() {
     return "ContactInfo(phoneNumber=" + this.phoneNumber + ", address=" + this.address + ")";
  }

  public int hashCode() {
     return (this.phoneNumber != null?this.phoneNumber.hashCode():0) * 31 + (this.address != null?this.address.hashCode():0);
  }

  public boolean equals(Object var1) {
     if(this != var1) {
        if(var1 instanceof ContactInfo) {
           ContactInfo var2 = (ContactInfo)var1;
           if(Intrinsics.areEqual(this.phoneNumber, var2.phoneNumber) && Intrinsics.areEqual(this.address, var2.address)) {
              return true;
           }
        }

        return false;
     } else {
        return true;
     }
  }
}

Looking specifically at those ordered component methods, we see that they return the phoneNumber, and address fields, in order.

@NotNull
public final String component1() {
  return this.phoneNumber;
}

@NotNull
public final String component2() {
  return this.address;
}

When we have a data class, we automatically get these ordered components for destructuring class declarations. This is what we were seeing in that first snippet of code we decided to evaluate. Because data classes are so simple to create, this feature can be used in many places. You can use it to return multiple related values from a function, and to iterate through a map.

for ((phoneNumber, address) in addressBook) {
 // Do something with phoneNumber and address
}

Summary

Learning a new language is fun, and we can make it less of a hurdle by applying the knowledge we already do have. This was one example of how we can use our knowledge of Java to get to know some unfamiliar Kotlin code. Try it yourself next time you run into something you wish you  knew more about!

Victoria was drawn to programming because of its potential to help people in a meaningful way. She is currently a Software Developer at Collective Idea, building mobile and web applications. The conferences she has spoken at have been an enjoyable way to connect with the technical community, and exchange information with others. In her spare time, Victoria enjoys dancing, and curling up with a good book.

You can follow her on Twitter or visit her website website at victoriagonda.com

Review Of Kotlin For Android Developers

Review Of the Book Kotlin For Android Developers

This is a review of the book Kotlin For Android Developers by Antonio Leiva, an Android Engineer working for an international company.

When you have to pick an educational book the first thing you have to understand is:

  1. what kind of book is
  2. whose the book is for

When it comes to books aimed to teach a new programming language they can roughly divided in two groups: theoretical and pragmatic ones. A theoretical book can be a 1000+ page book that teach all the aspects of the language, from the platform to each construct, usually in a logic order of ascending difficulty. Instead a pragmatic book teaches a language explaining the concepts, while you meet them in the course of building something, like an app.

A book may be too short or change arguments too quickly for a beginner audience or, vice versa, it might have a too slow pace for an advanced user. Granted, some books are just bad, but usually the problem is that the reader picked the wrong book.

Audience Of The Book

The title itself of the book Kotlin For Android Developers does a good job in clarifying its type and audience: it is a pragmatic book for experienced Android developers that want to pick up Kotlin. Which means that it builds upon your Android knowledge to teach you how to do with Kotlin the stuff you already know to do with Java.

To put in another way: the book does not explain how to create Android applications, if you do not already know how to do that. In fact, if you are not an experienced Android developer, you will not understand what is going on or why somethings matters. Probably you will not even understand Kotlin that well.

This also means something that might be obvious to some, but not all: there is very little theory. You should already know how the tools work (e.g., Gradle) and what things like delegates or lambda are. Only the chapter on Generics explains a bit of the theory behind them. Also, typically the issues with using a certain feature are not discussed, unless the issue is related to the Kotlin approach.

For instance, when listing the operators that you can overload that is what the book has to say about identity comparison in Kotlin:

Operators === and !== do identity checks (they are == and != in Java respectively)
and can’t be overloaded.

─ Chapter 11, p. 49

In short, if you an expert programmer that complains constantly about filler content, you are the perfect audience for this book. If you are a novice that needs hand-holding you should look elsewhere and maybe come back later to this book, once you have covered your basis.

Structure Of The Book

The book does not really have a formal structure, for the most part: there are 30 short chapters about several aspects you will encounter developing an Android app. An Android developer might notice that the order of the chapters resembles how a real app is developed: you create a working app as soon as possible and then you refactor it to make it beautiful.

Although to be fair most of the time the chapters does not seem to follow any particular order. We cannot really understand if there is any reason to explain control flow expressions in chapter 22 of 30. On the other hand, given the audience of the book, this is not really a problem because you are supposed to already know your way around an Android app.

In our opinion, this approach makes sense given the audience (developers with experience on Android). Busy developers can jump quickly to the point they are interest into, while skipping parts that are not extremely important for them right now. Experts do not need someone to draw the path for them, they need pointers to find quickly the information they are looking for.

There are only a few minor issues related to the order of topics. For example, reified generics are discusses before the chapter on generics; the REPL and the online playground are not mentioned in the Getting ready chapter, but in the introduction of the chapter about classes.

The internal structure of each chapter is more consistent: there is usually a problem and the code that solve it, all related to a weather app that is used throughout the book. The code of each chapter is presented in its entirety in the companion repository of the book. The reader is constantly reminded of the repository. Also, frequently the author note that the chapter only discuss the major modifications to the code and not everything that is in the repository. We think that code should be at the center of books about programming, so we really liked this approach.

There are a few chapters that just list, or explain, things about Kotlin, without any reference to the app. For example, chapter 11, that lists which operators you can overload, or chapter 18, that lists collections and related operations of the Kotlin standard library.

Content Of The Book

The book covers all the main aspects of Kotlin: from variables and null safety to generics and lambdas. So there is no complain to be made there. They are also covered in pragmatic terms, you are rarely going to see a few pages without any code. When this happens is usually because of the few things that needs an explanation, or a list, like the operators that you can overload. There is also a chapter for coroutines, an experimental features of Kotlin 1.1, which is a nice surprise. Of course, all the content is explained with Android development and issues in mind.

The book also covers a few essential libraries and tools: Anko and the Kotlin Android Extensions. Anko is a library composed of several modules and many of them are used in the book: Anko SQLite, Anko Coroutines, etc. The addition of this library, which will probably be used by almost all developers, is a good example of the benefits of the pragmatic approach of the book. You are going to learn most of what you are going to use in your everyday development for Android with Kotlin.

The only important thing that the book does not talk about is Anko Layouts. And the reason is that the author does not care about it, which is a perplexing choice or, at the very least, a perplexing justification.

Anko is a powerful library developed by JetBrains. Its main purpose is the generation of UI layouts by using code instead of XML. This is an interesting feature I recommend you to try, but I won’t be using it in this project. To me (probably due to years of experience writing UIs) using XML is much easier, but you could like this approach.

─ Chapter 7, p. 33

Maybe it is true that most Android developers are used to XML, just like author, but it seems an odd reason to exclude something, especially since the author itself present it as the main purpose of the library.

In any case, with this choice the author miss the chance to talk about type-safe builders, which can be useful to build also HTML layouts or any kind of type-safe hierarchical data.

Summary

Once you understand the audience of the book you are going to agree that it has only a few flaws. The content you need is all there, although you could argue that some chapters devoted to theory are a bit thin.

For instance, the first chapter, that explains why you should use Kotlin for Android is a bit short. It does not really introduce all the good things of Kotlin (e.g., Anko) that the book will talk about, and it does not present well the one it mentions (e.g. Expressiveness shows only data classes and not other features linked to expressiveness). But this is mostly nitpicking.

The structure of the book can be perplexing. However, since the book is for experienced Android developers, this might be annoying for some, but not problematic for the target audience.

On the other hand if you know Android and prefer a pragmatic and code-first approach this book is the best you can find to learn Kotlin to use it for your Android apps.

There is no filler content, not a word more than the one you need to get you going and there is no quicker way to learn how to use Kotlin in your job.

A nice touch is that the author periodically updates the book, also based on the feedback he receives. The updates are sent automatically for the digital version. Buyers of the physical one can ask the author for free access to an updated digital edition.

Disclaimer: the author gave us a copy of the book for the review but we do not have any agreement for affiliate marketing or any other interest in recommending this book.

Kotlin Courses

Kotlin Courses: Reviews And Comparison

You have seen the benefits Kotlin can bring to you, however you have to learn Kotlin. You can do learn it on your own, pick a book or get access to a course.

The problem is to you have to figure out which course is best for you: we have reviewed the most relevant ones and in this article we are going to give you the information you need to pick the course that is right for you.

If none of this course is what you are looking for you can still look into our list of 100+ Resources To Learn Kotlin The Right Way.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


What you will find in this article?

First of all you will find the review of the courses, divided in four groups. Depending on the level at which you want to learn Kotlin, your background and if you are interested specifically for Android development you can pick one or more specific groups to investigate them further.

The following table provides a summary of the characteristics of the available courses.

Name Platform Type Length Price ($)
Kotlin for Java Developers Treehouse Introductory 02:41 25-49 (subscription)
Learning Kotlin for Android Development Lynda.com Introductory 01:01 15-25 (subscription)
Introduction to Kotlin Programming / Advanced Kotlin Programming Safari (O’Reilly) Course for developers 05:14 / 03:00 39 (subscription)
Introduction To Kotlin Udemy Course for developers 04:55 50
Kotlin Fundamentals Pluralsight Course for developers 04:47 29 (subscription)
Kotlin for Beginners: Learn Programming With Kotlin Udemy Course for non-developers 06:37 95
The Essential Kotlin Programming Course (Android Developers) Udemy Course for non-developers 25:25 150
The Complete Kotlin Developer Course: Become A Pro! Udemy Course for non-developers 04:04 30
Kotlin & Android Developer Masterclass – Beginner to Advanced Udemy Course for Android 19:43 200
The Complete Android Kotlin Developer Udemy Course for Android 26:27 200

Notes: if the price indicate a subscription it is a monthly subscription to a whole library of courses including the one reviewed; Udemy pricing varies wildly and can be lowered even by 90% during promotions; the length of a course could vary since it can be updated.

Beside helping you picking up the right course for you we have a few more considerations to share:

Introductory Courses

A stilyzed representation of programming

Kotlin for Java Developers is a relatively short journey (it lasts 161 minutes) to learn the basics of Kotlin through the development of card games for Android. The course is meant to introduce Android developers to Kotlin and help them get started or evaluate the adoption of Kotlin in their professional life.

Learning Kotlin for Android Development is a short one-hour course for learning the basics of Kotlin and exploring how it can help in your Android development, all by creating a simple app for Android. It also touches on the setup of Android development (eg. creating an emulator) and converting a Java app in Kotlin.

Courses For (Java) Developers

A cup, usually a symbol of Java, with a Kotlin logo

These are course for developers, especially experienced Java programmers. They can be basics or in-depth, but usually takes advantage of previous Java knowledge to skip most of the theory.

Kotlin Programming By O’Reilly

Introduction to Kotlin Programming and Advanced Kotlin Programming are two O’Reilly courses from Hadi Hariri, VP of Developer Advocacy at JetBrains, the company that created Kotlin. The courses do not strictly require a knowledge of Java, in the first one there is even short introduction to the JVM. Having said that, there is one part dedicated to the interoperability with Java, so if you know Java or any other JVM language you are going to get the most out of it.

In any case you need to be a developer. The course covers well how to do things in Kotlin, but not the theory behind the features. The first course covers the basics, that you will use in your everyday job: everything from conditional expressions to the fundamentals of Kotlin lambdas. The second one covers advanced topics like metaprogramming, delegation  and deeper examination of Generics and Functions.

Introduction To Kotlin

Despite the name, Introduction to Kotlin it is a relatively in-depth (5 hours) course to explain Kotlin to Java developers. Technically the overview says only that Java knowledge is beneficial, but there are comparison to Java here and there. Furthermore many reviews laments a very fast pace, so probably Java experience is needed to have the best experience.

The course is essentially divided in two parts: the first covers Kotlin syntax and how to use all its features, even higher-order functions; the second one is about the advanced usage of Kotlin collections and reflection.

The second part seems a bit rushed, I mean there is even a section titled Odds & Ends. On the other hand the section on the usage of the Collections functions of the standard library can be quite useful especially if you come form Java and you have never used a language like C# (with LINQ).

Kotlin Fundamentals

Kotlin Fundamentals is a good course for experienced Java developers with a puzzling title. In fact the course explore all you need to know in your professional life to use of Kotlin in the best way, especially interacting with Java. For instance there is a few sections on how functional interfaces and nullability of Kotlin interact with Java. A more apt title would have been something like Real Life Kotlin For Java Developers.

Having said that, the course offers brief introduction to the topic at hand before developing it. It also focuses on pragmatic problems with can be useful for professional developers and, of course, puzzling for beginners. For instance, there is a section titled Working with Infinite Collections that explains Sequences in Kotlin, an expert would know why it makes sense to care about the issue, while a beginner would ask himself what infinite means.

Kotlin Courses For Non-Developers

A clueless person in a lab coat typing on an old computer

These are course for complete beginners in programming, you should expect and hope for a lot of theory.

Kotlin For Beginners: Learn Programming With Kotlin

Kotlin for Beginners: Learn Programming With Kotlin (see note) is a course to learn programming with Kotlin starting from scratch. And with that we mean that really you do not need to know anything even about Udemy, the platform the course uses. In fact there is an introductory video to explain the features of Udemy itself (eg. how to speed-up the video, where to find the companion resources, etc.) and how to best take advantage of the course. You cannot get more beginner friendly than that.

The course will teach you both the basic features and concepts of programming, in general, and the Kotlin language, in particular. Concepts and Kotlin idioms are explained together, for instance the difference between expression and statement is explained while explaining the advanced usage of if and when. However there are also theoretical sections, for example one on binary and hexadecimal numbers.

There are quizzes and coding challenges (i.e. exercises) to help your test and practice your programming skills. The course also offers solutions accessible through GitHub. It is a nice touch and a good way to introduce a professional tool to beginners.

In terms of content, apart from the obvious basics (e.g. variables, lists, etc.), there are a few sections that covers all aspects of object-oriented programming, everything from what methods are to singletons. Both theory (eg. information hiding) and practice are explained. It is important to note that you will not find explanation of the more advanced functional features of Kotlin, such as lambdas and higher order functions.

We would like to thank the author of this course for having given us free access to it. He has also prepared a special offer for our readers, following that link you will get the course for a reduced price.

There is no affiliate marketing agreement between SuperKotlin and the author or Udemy. That is to say we do not receive any money if you purchase the course with a discount or to show you this review or for anything else.

The Essential Kotlin Programming Course (Android Developers)

The Essential Kotlin Programming Course (Android Developers) is a very in-depth course (25 hours) that explains at length the topic at hand and then also explains how it works in Kotlin. Let’s say that there is one hour introductory section that explains the features of Kotlin and what are object oriented and functional programming.

The rest of the course is equally thorough in explaining the theory and how it applies to Kotlin programming. For instance it takes its time (2 hours) to explains Kotlin Collections of the standard library: what they are, the different functions, how they relate to the corresponding Java collections…

The course is both theory and practice, not just because it explain how doing things in Kotlin, but also because there are five hours of exercise lessons. In short this course is the closest equivalent to a traditional university course. Which is great if you think that online courses tend to be too quick and pragmatic, leaving out how things works and why they work that way.

The course lacks parts about Concurrency and Metaprogramming, that are still in the works. The course explains how to use programming tools (ie. IDEs) and in particular Android Studio (including the Emulator), but apart from that there seems to be little on the specifics of Android development.

The Complete Kotlin Developer Course: Become A Pro!

The Complete Kotlin Developer Course: Become A Pro! is a good course for beginners that overpromise a bit. We mean that the course is short (4 hours) for a complete course intended to transform a beginner in a professional developer. It basically covers the basics of programming and the syntax of Kotlin: from variables to what is object oriented programming.

The course is cheap and short for a complete course, so in some sense it is the opposite of some other complete courses, but it is also very popular, so many people find it worthwhile. If you want to quickly and cheaply learn programming and understand that the course does not actually prepare you to become a professional, it can be a good choice.

Courses For Non-Developers Interested In Android

Audience cheering for the announcement of Kotlin support on Android

These are course for people that do not know anything about programming except that they want to create mobile apps for Android, probably for making money with apps.

Kotlin & Android Developer Masterclass – Beginner to Advanced

Kotlin & Android Developer Masterclass – Beginner to Advanced is a comprehensive course (19 hours) that teaches Kotlin in the context of Android development. The course is essentially divided in two parts: the first explains the basics of programming with Kotlin (eg. variables, functions, etc.), the second one covers Android development, everything from using Android Studio to user interfaces, databases and web services.

When it comes to content the only topic that is not explained explicitly are functional features of Kotlin, although some of them are used in practice, for instance when talking about listeners. This is not a big oversight if you only care about Android development, but it matters if you are more interested in a comprehensive Kotlin programming course.

The course could probably use an editor to review the texts for style and clarity, for instance the title of the lessons are unnecessarily complex at times and do not follow a coherent style. The actual lesson videos follow an understandable script. The organization of the course is also a bit perplexing, for example: a lesson to explain return types of functions is inside a section dedicated to object oriented programming; arrays are explained after advanced objected oriented programming.

The Complete Android Kotlin Developer

The Complete Android Kotlin Developer is a very in-depth course (26 hours) to learn programming and Android development using Kotlin. It touches so many topics that we cannot really cover them all, but in short we can say:

  • it starts by covering the basics of programming, both in theory and with Kotlin, with things such as conditional expressions up to object oriented programming
  • it continues with many example Android apps that are used to explain interaction and different layouts available in Android
  • it passes to advanced Android apps to shows how to use important programming tools like databases (SQLite and Firebase), web services and specific Android features like sensors and media player
  • it ends with complete example apps to put everything together

It is one of the longest, most expensive and most followed course for Kotlin on Udemy. It is designed to transform a normal person in a professional junior Android developer. Which means that many people want to become professional developers and they find this course good for their needs. The downside of covering so many topics is that many reviewers mentions that the rapid switch from one topics to the next can leave some people hanging. So keep that in mind.

The only thing that does not cover well is making mobile games. We think that is for the best because to cover the subject professionally it would require a whole new in-depth course and Kotlin might not be the best choice for that kind of apps. However it is relevant to note it for complete beginners.

When To Pick A Book, An Online Course Or In-person Training

There are four main different approaches that you could decide to take to learn a programming language:

  1. To learn on your own: using only free online resources and building your custom learning program
  2. To buy a book and follow it
  3. To get access to an online course, follow the lessons and do the exercises
  4. To attend in-person training

The option number zero does not require any monetary investment, however it is the one that requires the most time and pose the most risks, because the person could miss important subjects or using sub-optimal resources. We have already linked our list of resources to help you if you want pick this way, so let’s focus on the other three instead.

These three options offer different balance on different aspects.

  • The risk: the more supervision you have, the more you can be reassured of being on the right track, your errors can be caught sooner.
  • Time to learn: the less supervision you will get, the more you will rely on trial-and-error. It means it will take longer to really master the content.
  • Investment: the investment in term of money grows significantly with the level of supervision. A book can cost tens of euros/dollars, a MOOC could go from the tens to the hundreds of euros/dollars, while in person training will typically be in the thousands of euros/dollars
  • Access: buying books and access to MOOCs is very easy. Once you got access you can read a book everywhere, while typically you will consume a MOOC at your desk, ready to work on exercises. In person training instead requires to hire a teacher and agree on a date to deliver the course, so access is less immediate to get
Kotlin courses vs in person training vs book

Book vs MOOC vs In-person training

So what is the best solution for you to learn Kotlin?

It really depends on the value of your time and the amount of money you can afford to invest.

If you are a student with the head full of dreams and an empty wallet the answer is clear: you should just use free online resources or maybe buy a book for 20-30$. That would be a wise investment. After all, if it takes a few more months to learn Kotlin it will not make a huge difference for you.

As a freelancer or a young professional probably a MOOC is the best compromise: you get lessons from knowledgeable teachers and you typically get exercises to evaluate your progress. MOOC are also usually updated more frequently than books, so you get fresher content, in line with the evolution of Kotlin. Maybe there is also a forum where you can get answers to a few of your questions.

If you are a seasoned professional or you work at a company with an healthy business than in-person training could be the most reasonable choice for you. You cannot afford to learn by trial-and-error, you do not have the time to look for the best resources online and evaluate them. Taking a few months to learn Kotlin would have an impact on the business as projects are delayed or move on slowly. Considering the cost of an employee for a company your time is extremely expensive. Whatever can save you time justify significant investments in terms of money.

So depending on where you are in life, you can value different things and different ways to learn could make more sense for you.

Books For Self-Learners

Historically the favorite tool for learners has been a book, or many books. It is a tool that can be used both by self-learners and students in a regular course or learning institution. The advantage of learning on your own is that you can choose your own pace and pay less than a traditional course, since a book cost much less than a teacher.

The disadvantage is the lack of a person that can help you understand the material, the loneliness of the experience and the static nature of a book. A static nature means that the information can become outdated and it is always in the same form and the same pacing: a written text with a lot of repetitions to insure everybody can understand.

Learning Online: MOOC

A new tool was created and delivered through the internet that could overcome some of the limits of books: MOOC (Massive Open Online Courses). While there is not a rigid formula behind a MOOC, they usually share a few characteristics:

  • different types of videos (lessons, lectures, etc.) and content (exercises, references, etc.)
  • a minimal structure in the learning material
  • permanent access to content that is regularly updated
  • a learning community
  • a teacher available to help through asynchronous methods of communication

The learner must still be willing to put the effort and to learn the material mostly on its own. But if he encounters some problem the community or the teacher can help and they can always provide support and motivation to learn. The content is better organized, provided in different forms. For instance you can have video, test quizzes and even a short reference document. It is also usually updated regularly.

The downside of a video course is that the material is harder to search and access and the cost is higher. It is harder to search and access because it is a video and not a text, so neither humans nor software can quickly scan it. It cost more because it is more expensive to produce and a teacher is usually available to help students.

In-person Training For Learning Kotlin

A lot of devices

Apart from a few cases, usually a business need a tool that can give a definitive time frame for getting the results it needs. That is because planning is fundamental in a business: if a project must be started now, delaying it because the personnel does not have the right skills is going to cost lost revenues.

Preferably it should also be a tool that can save time by being adaptable to the specific needs of the business. There is no need to teach your developers how to make Android application in Kotlin, if you do not plan to create them. Also, a course should be based on the specific background of your personnel.

In the case of learning that tool is a traditional face-to-face course delivered by a teacher, that has experience in the subject and in teaching to professionals. We can provide that: we have courses designed for professional developers and technicians or scientists. Our courses can prepare both Java and non-Java developers to create professional software in idiomatic Kotlin. We can also teach scientists, and all other kinds of technical personnel, scripting and basic programming in Kotlin. If you are interested look at our page for Courses.

Summary

There are may ways to learn depending on where you are in life, how valuable is your time and how you prefer to learn. Online courses are a good options for many of you and we hope that this article will help you pick the right one for you. Whatever way you choose we hope you are going to learn Kotlin soon and have fun doing it.

We are not connected to any author or platform of these courses. We do not have any affiliate marketing agreement with them and we are not getting anything to review any of them.

Compile Kotlin to native executables: hands on experience

Kotlin is becoming the one language you can use in every context:

  • it can be compiled to JVM bytecode and reuse JVM libraries
  • it can be transpiled to JavaScript and use JavaScript libraries
  • it can now also be compiled to native code reusing native libraries

While the JVM and JavaScript target are already mature, the native target is more recent and it is still experimental. However we decided to take a look and check ourselves what is already possible to do.

We are working with version 0.3 which supports:

  • Mac OS X 10.11 and later (x86-64), host and target
  • Ubuntu Linux x86-64 (14.04, 16.04 and later), host and target
  • Microsoft Windows x86-64 (tested on Windows 7 and Windows 10), host and target
  • Apple iOS (arm64), cross-compiled on MacOS X host
  • Android arm32 and arm64,cross-compiled on Linux or MacOS X host
  • Raspberry Pi, cross-compiled on Linux host

In other words you can target all the 3 main OS for the Desktop, the 2 main OS for mobile, and Raspberry Pi.

What we are going to do

Our goal is to check in practice how we can use Kotlin native today. We are going to build a simple application using a C library (libpng).

We are going to build an application that generates a simple image: the Kotlin logo. Our program will take as input the desired size of the image and generate the logo. The logo will be saved in PNG format, and that is why we need to use libpng.

We are going to see:

  1. How to configure the project using a specific gradle plugin
  2. How to build the Kotlin library manually
  3. How to launch the compiler manually
  4. How to write the code

Setup the project using the kotlin native gradle plugin

The simplest way to build a project using Kotlin native is to use gradle as your build system and the corresponding plugin.

To get started you need to:

  • create gradle.properties
  • create build.gradle
  • create the src/main/kotlin directory for your Kotlin source code
  • typically you want also to run gradle wrapper. Basically it creates a little script that install gradle if needed. Read more here.

Let’s see what we need to insert in those you files.

gradle.properties

konan.version=0.3

We specify just the version of the kotlin native compiler we want to use.

build.gradle

buildscript {
    repositories {
       mavenCentral()
       maven {
           url  "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
       }
   }

   dependencies {
       classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.3"
   }
}

apply plugin: 'konan'
apply plugin: 'idea'

konanArtifacts {
    LogoGenMacbook {
        target "macbook"
    }
}

In this case the gradle script contains also the IDEA plugin so that we can generate an IDEA project by running ./gradlew idea.
We have then defined a target to build the executable for macos. You could want to pick another target. Valid targets currently are:

  • android_arm32
  • android_arm64
  • iphone
  • iphone_sim
  • macbook (for macOS)
  • mingw (for Windows)
  • linux

Hello world from native

src/main/kotlin/logogen.kt

fun main(args: Array<String>) {
   println("Hello from native!")
}

At this point we can compile everything with ./gradlew build. Then we can just run ./build/konan/bin/LogoGenMacbook.kexe to execute it and voila!

Using native libraries

While printing on the screen can be exciting at first after a while we could want to move forward. For doing anything meaningful we are going to need some native library. In this example we are going to use libpng, but the same procedure applies to use any library.

Note that you can reuse all native libraries that follows the C ABI. For other languages like C++ or Rust you could have to wrap the libraries with C before being able to use them, or use existing C bindings, where available.

Install native library

First of all we could want to install the library on our system. This is technically not needed: we could just download it somewhere and specify the include directory and the linker options.

On mac I ran:

brew install libpng

Define def files

Now we need to make Kotlin code aware of the C functions we want to use from libpng. To do that we just list the header files we want to use.

src/main/c_interop/png.def

headers = /usr/local/include/png.h stdio.h stdlib.h string.h math.h

You could notice that we included both headers from libpng and others from the standard library. Now, we could be tempted to define another def file for the standard library but that did not work for me. Why? Because when importing png.h the compiler also imports all files included by png.h, including some from the standard library. For the corresponding structures (like FILE), it creates a Kotlin wrapper. So we end up with two different FILE: one from the standard library and one for png, that was imported implicitly. This cause all sort of compilation errors, so let’s make our life easier. This is something that will need to be sorted out eventually, but for now let’s use a workaround and define one def file with everything we need.

Add linking instructions

We need also to update build.gradle to use our library:

// This is new
konanInterop {
   png {
       defFile 'src/main/c_interop/png.def'
   }
}

konanArtifacts {
    LogoGenMacbook { 
        linkerOpts "-L/usr/local/lib -lpng" // we added this line
        target "macbook"
        useInterop 'png' // and this one
    }
}

Import

Now we need to import the C functions and structures in our Kotlin file. We do this with this line:

import png.*

And that is it, we are now ready to use libpng from Kotlin!

What our application will do: logos, logos of all sizes!

Our application is going to generate the Kotlin logo of the size we want.

You can download the Kotlin logo from the official website but our program will instead generate it programmatically and save it to a PNG image.

Let’s draw our first image

Let’s start with a first version that will generate a logo of 500×500 pixels. It will generate the logo using three bands of homegenous color. We will add the nice gradient of the real logo in a successive iteration.

import kotlinx.cinterop.*
import png.*

val PNG_LIBPNG_VER_STRING = "1.6.29"
val PNG_INTERLACE_NONE = 0
val PNG_COMPRESSION_TYPE_BASE = 0
val PNG_FILTER_TYPE_BASE = 0

data class Color(val r: Int, val g: Int, val b: Int)

val ORANGE = Color(244, 133, 25)
val BLUE = Color(39, 137, 217)
val WHITE = Color(255, 255, 255)

fun setRGB(rowBuffer: CPointer<ByteVar>, y: Int, x: Int, color: Color) {
     rowBuffer.plus(3 * x + 0)!!.reinterpret<ShortVar>(()[0] = color.r.toShort()
     rowBuffer.plus(3 * x + 1)!!.reinterpret<ShortVar>(()[0] = color.g.toShort()
     rowBuffer.plus(3 * x + 2)!!.reinterpret<ShortVar>(t()[0] = color.b.toShort()	
}

fun draw_logo(width: Int, height: Int, filename: String) {
   val fp = fopen(filename, "wb")
   if (fp == null) {
      println("Unable to open the file")
      return
   }

   val png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, null, null, null)
   if (png_ptr == null) {
      println("Unable to create the png (png_create_write_struct failure)")
      return
   }

   val info_ptr = png_create_info_struct(png_ptr)
   if (info_ptr == null) {
      println("Unable to create the png (png_create_info_struct failure")
      return
   }

   png_init_io(png_ptr as CPointer<png_struct>, fp)

   val bit_depth = 8
   val color_type = PNG_COLOR_TYPE_RGB

   png_set_IHDR(png_ptr, info_ptr, width, height,
         bit_depth, color_type, PNG_INTERLACE_NONE,
         PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE)

   png_write_info(png_ptr, info_ptr)

   val rowBuffer = nativeHeap.allocArray<ByteVar>(3 * width + 3)
   for (y in 0..(height-1)) {
      val yProp = (y+1).toFloat()/height
      for (x in 0..(width-1)) {
         val xProp = (x+1).toFloat()/width
         val topBand = yProp <= 0.5 && xProp <= (0.5 - yProp)
         val middleBand = !topBand && xProp <= (1.0 - yProp)
         val lowerBand = yProp >= 0.5 && ((xProp <= 0.5 && xProp>= (1.0-yProp)) || (xProp>=0.5 && xProp <= yProp))
         if (topBand || lowerBand) {
            setRGB(rowBuffer, y, x, BLUE)
         } else if (middleBand) {
            setRGB(rowBuffer, y, x, ORANGE)
         } else {
            setRGB(rowBuffer, y, x, WHITE)
         }
      }
      png_write_row(png_ptr, rowBuffer)
   }

   png_write_end(png_ptr, null)

   fclose(fp)
   println("Logo of size $width x $height generated in $filename")
}

fun main(args: Array<String>) {
   draw_logo(500, 500, "logo.png")
}

We have a bunch of calls to libpng functions. You can look at the documentation of that library if you are interested in details, we will mostly comment the Kotlin stuff.

Our main contains just a call to draw_logo. This function is where we create a PNG and save it to file. Most of the code is just boilerplate. The interesting part is composed by the two annidated loops over the height and the width of the image. Basically for each pixel we want to calculate its proportional position (xProp, yProp). These are values from 0 and 1, where 0 for the xProp indicates the left, 1 indicates the right and 0.5 indicates the middle. Similarly for yProp 0 indicates the top, 1 the bottom and 0.5 the middle. For each pixel we want to understand in which band it belongs. Take a look at this picture:

You can compare the picture with the expressions to calculate to which band a pixel belong:

val topBand = yProp <= 0.5 && xProp <= (0.5 - yProp)
val middleBand = !topBand && xProp <= (1.0 - yProp)
val lowerBand = yProp >= 0.5 && ((xProp <= 0.5 && xProp>= (1.0-yProp)) || (xProp>=0.5 && xProp <= yProp))

Once we have figure out the band we just paint the pixel with the color used for that band: BLUE for the top and lower band, ORANGE for the middle one, and WHITE if the pixel does not belong to any band.

To set the single pixels we use the setRGB function. In this function we receive an array of bytes (rowBuffer). Now, it contains a sequence of pixels, one after the other. For each pixel it contains the red, green, and blue components. We calculate the position of the component of interest for the pixel of interest. For example, for the red component we use rowBuffer.plus(3 * x + 0). Ok, this is where we want to write the value of the red component. However there is an issue because we cannot use a byte, given it is a signed value in Kotlin, so it can hold values between -128 and 127, while we have values between 0 and 255. So we use a short instead. We cast the byte array to a short array and we write the first element. Note that in this way we override the next pixel, so calls to setRGB need to be executed in order. Support for unsigned values is one of the issues that needs to be sorted out.

Consider program arguments

The next step is to consider the program arguments. We expect the user to tell us the size of the logo he or she wants.

val MAX_SIZE = 2000

fun main(args: Array<String>) {
   if (args.size != 2) {
      println("2 arguments expected, while we received ${args.size}")
      return
   }
   val width = args[0].toIntOrNull()
   val height = args[1].toIntOrNull()
   if (width != null && height != null && width in 1..MAX_SIZE && height in 1..MAX_SIZE) {
      draw_logo(width, height, "logo_${width}x$height.png")
   } else {
      println("Please specify positive dimensions equal or lower than $MAX_SIZE")
      return
   }
}

We need to check that two values are provided and that both are valid. We accept only integers between 1 and 2000. If both are valid we move on with the generation. We also use the width and the height to determine the name of the image file.

And here there are our logos of all sizes:

Draw a gradient

Our logos look nice but the original is still nicer because it use a gradient, so the different bands are not homogeneous but the color changes as we move from across the band. Let’s try to replicate that.

We need first to add a bunch of elements:

data class Point(val x: Float, val y: Float) {
   fun distance(other: Point) = sqrt(pow((x - other.x).toDouble(), 2.0) + pow((y - other.y).toDouble(), 2.0))
}

data class ColorSource(val point: Point, val color: Color)

class Band(val colorSources: List<ColorSource>) {
   fun color(point: Point) : Color {
      val invDistances = colorSources.map { 1.0f/it.point.distance(point)}
      val sumInvDistances = invDistances.sum()
      var r : Double = 0.0
      var g : Double = 0.0
      var b : Double = 0.0
      colorSources.forEachIndexed { i, colorSource ->
         r += colorSource.color.r * (invDistances[i]/sumInvDistances)
         g += colorSource.color.g * (invDistances[i]/sumInvDistances)
         b += colorSource.color.b * (invDistances[i]/sumInvDistances)
      }
      return Color(r.toInt(), g.toInt(), b.toInt())
   }
}

val TOP_BAND = Band(listOf(
      ColorSource(Point(0.0f, 0.0f), Color(24, 141, 215)),
      ColorSource(Point(0.5f, 0.0f), Color(128, 110, 227)),
      ColorSource(Point(0.0f, 0.5f), Color(0, 149, 213))))

val MIDDLE_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.0f), Color(248, 137, 9)),
      ColorSource(Point(1.0f, 0.0f), Color(248, 137, 9)),
      ColorSource(Point(0.0f, 0.5f), Color(215, 103, 128)),
      ColorSource(Point(0.0f, 1.0f), Color(199, 87, 188))))

val LOWER_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.5f), Color(128, 110, 227)),
      ColorSource(Point(0.0f, 1.0f), Color(0, 149, 213)),
      ColorSource(Point(1.0f, 1.0f), Color(128, 110, 227))))


And then to modify how we calculate the color in the inner loop of our draw_logo function.

...
val band = when {
   topBand -> TOP_BAND
   middleBand -> MIDDLE_BAND
   lowerBand -> LOWER_BAND
   else -> null
}
val color = band?.color(Point(xProp, yProp)) ?: WHITE
setRGB(rowBuffer, y, x, color)
...

What we are doing here?

For each band we write down the colors of the extremes. You can see the extremes in this picture:

And these are their values:

val TOP_BAND = Band(listOf(
      ColorSource(Point(0.0f, 0.0f), Color(24, 141, 215)),   // T1
      ColorSource(Point(0.5f, 0.0f), Color(128, 110, 227)),  // T2
      ColorSource(Point(0.0f, 0.5f), Color(0, 149, 213))))   // T3

val MIDDLE_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.0f), Color(248, 137, 9)),    // M1
      ColorSource(Point(1.0f, 0.0f), Color(248, 137, 9)),    // M2
      ColorSource(Point(0.0f, 0.5f), Color(215, 103, 128)),  // M3
      ColorSource(Point(0.0f, 1.0f), Color(199, 87, 188))))  // M4

val LOWER_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.5f), Color(128, 110, 227)),  // L1
      ColorSource(Point(0.0f, 1.0f), Color(0, 149, 213)),    // L2
      ColorSource(Point(1.0f, 1.0f), Color(128, 110, 227)))) // L3

For each pixel we want to calculate the color depending on how close it is to one of the extremes. In practice we calculate the closeness as the inverse of the distance between each two points. For each pixel we calculate this inverse distance to all the extremes and the sum. Then we calculate the color as the pixel as a proportion considering the closeness and the color of each extreme. This is what we do in Band.color.

And this is what we get:

It is still not as cool as the original one but we are getting closer.

Building everything manually

In this article we have seen how to use the gradle plugin to compile things. However if you prefer to not use it you can also do everything without.

Build the native compiler locally

You may want to compile the native compiler yourself.

To do this you should first clone the repository:

git clone https://github.com/JetBrains/kotlin-native.git

Then you could build it with these two commands:

./gradlew dependencies:update
./gradlew dist

And here you go, now you have the bleeding edge version of the compiler to play with!

Build library manually

Kotlin native is experimenting with its own format for libraries. If you want you can generate a library by running this command:

cinterop -def src/main/c_interop/png.def -copt "$CFLAGS" -target macbook -o build/c_interop/png

Use the compiler manually

If you want to invoke the compiler manually this is how you can do that. Note that here we are using the library we compiled at the previous step:

konanc $COMPILER_ARGS -target macbook src/main/kotlin/logogen.kt -library build/c_interop/png -linkerOpts "-L/usr/local/lib -lpng" -o build/bin/logogen

Summary

Is Kotlin becoming the new solution for “write it once, run everywhere?”

This is a possibility, I think. There is code we need to execute on different platforms. I do not think we will get applications that run on different platforms like the web, iOS and Android because the interactions are different and the user expectations are different. However we need and will probably get common business logic, common libraries. Kotlin seems an interesting language to deliver that.

That said it is possible to build something today, with the Kotlin native compiler as it is but there is a big roadblock: the editor support.

We would like to thank Mario Zechner for his comments which helped improving the article.

Kotlin Javascript Target: Use Kotlin in the Browser

Kotlin Javascript Target: Use Kotlin in the Browser

This article is a tutorial and introduction to run Kotlin on the browser, by compiling Kotlin to JavaScript. We are going to see the simplest way to setup a project that use existing JavaScript libraries. We are also going to learn and use the awesome when expression of Kotlin. This expression is quite useful and a good example of the pragmatic approach of Kotlin. You will probably try to use it everywhere.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


How Kotlin Supports Multiple Environments

Some languages saves development costs relying on a existing intermediate language or platform. The language you write is compiled or transpiled to a different language. So the existing compiler and/or virtual machines can be reused. This is the approach that Kotlin adopts by running on the JVM, which in turns can run almost everywhere.

The problem is that there are also specific environments that cannot be supported by a virtual machine because of their constraints. Two examples are: the browser and embedded systems. To support development on the browser we have to use JavaScript. So if we do not want to write directly using JavaScript we still have to transpile to JavaScript because that is the only language available on the browser. Furthermore an incredible amount of effort has been spent to optimize JavaScript engines.

By transpiling Kotlin to JavaScript we can use it both for client and server web development (through Node.js).

Why Using Kotlin Instead of JavaScript

Given that the support for JavaScript is so widespread you may ask yourself why using Kotlin and not directly JavaScript for web development. The first advantage is that you can use Kotlin for everything. You can create a web service and desktop application targeting the JVM and the corresponding web client targeting JavaScript. The second one is that JavaScript is not a good language for developing large applications.

It is a well known problem that is also addressed by TypeScript, a language that also transpile to JavaScript whose motto is JavaScript that scales. An alternative to the better language approach is to use complex JavaScript frameworks like Ember.

Kotlin For JavaScript

The current implementation targets ECMAScript 5.1 but there are plans to eventually target ECMAScript 2015 also.

The Kotlin support for JavaScript is not skin deep, but is geared both to the language and the modules. The problems are with the tools and the inherent incompatibilities between languages with dynamic and static typing.

Kotlin include libraries to support the manipulation of the DOM elements and also graphical elements using WebGL. The Kotlin compiler can also create JavaScript modules compatible with different systems: AMD, CommonJS and UMD. AMD are usually used client-side, CommonJS server-side (node.js) and UMD unify both systems.

The Kotlin ecosystem is still Java-based even when targeting Kotlin. This means that you are using Gradle, Maven, etc. instead of the node.js or JavaScript tools. That is because the compiler itself that transpiles to JavaScript is written for the JVM.

There is an inherent problem of compatibility between a dynamic typing language like JavaScript and one with static typing like Kotlin. The issue is that there are no type information in JavaScript, but Kotlin need them to work. So to use JavaScript libraries with Kotlin you have two options:

  1. You add type information
  2. You signal to Kotlin to ignore type checks

We are going to see how to ignore later. To add this information there is no smart way to do it. There is only the hard way: do it manually. Fortunately the Kotlin creators have included ts2kt a tool that translate TypeScript declarations in Kotlin ones. So you may be able to reuse them, but compatibility is not perfect. In fact for this tutorial we tried to use it for D3.js and it did not work without errors. That is a complex library, so your mileage may vary.

Our Project: Drawing With D3.js

The project for this tutorial is based on the D3.js example called US State Map. The D3 (Data-Driven Documents) is a famous library to create interesting and complex data visualizations. Our project repository is available on GitHub.

Given that the original code is released under the GPL3 so will be the code of our example. The idea is quite simple: a map of the USA with its states visible and colored according to the (randomly generated) temperature data. A tooltip will be displayed when the mouse hover a specific state.

This looping video shows a generated map.

 

We are also going to add a simple table listing the temperature data.

The project only deals with client-based code and not server-based.

Setup

There are many supported ways to use Kotlin for JavaScript: Gradle, Maven, IntelliJ IDEA and using directly the compiler on the command line. The suggested way is to use Gradle. For this tutorial we choose to directly use IntelliJ IDEA instead. That is because if you come from a Java you probably already know how to use Gradle. And in any case there is good documentation available to discover what plugin and dependencies include.

While it is by no means hard adding a build automation system this is not the focus of this tutorial, so we opt to use the simplest way.

Kotlin JavaScript Project

All you have to do is creating a New Project and selecting Kotlin (JavaScript). The name of our project is KotlinFunWeb.

We are also going to use also a library to simplify the creation of HTML code called Kotlinx.html, instead of using string concatenation or interpolation. So download kotlinx-html-js from the binary repository and add it to your project by going into Project Structure.

Adding a Kotlin library

We put it under the lib directory. We have it created just under the root project directory, but you can put it wherever you want.

The next step is creating a .kt file inside the src directory. We chose the name main.kt, but the name is not relevant. This file will contain our Kotlin code for this tutorial.

For the moment it will contain only the following code to test that everything works:

import kotlin.browser.*
import kotlin.dom.*

fun main(args: Array) {
    document.getElementById("tooltip")?.appendText("The first step")
}

The ?. is necessary because the element could not exist, so the result of getElementBy could be null. In such case the call to appendText will not be executed, but there will be no error. Apart from that, it looks like normal JavaScript code.

The last step is to add index.html, a normal HTML file that will include the JavaScript code.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<div id="tooltip"></div>
<script type="text/javascript" src="out/production/kotlinfunweb/lib/kotlin.js"></script>
<script type="text/javascript" src="out/production/kotlinfunweb/kotlinfunweb.js"></script>
</body>

The key part are the two script tags: the first one include the standard KotlinJS library and the second one include our code transpiled to JavaScript.

Once you build the project the resulting structure should look like this:

The directory layout of the project

The files under the out directory, including the directory itself, are generated when you build the project. The .meta files include code to support reflection and you do not need them to run the project.

All that remains to do is to access the file index.html in a web browser to check the result.

The Generated JavaScript Code

The generated file KotlinFunWeb.js should look similar to this:

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'KotlinFunWeb'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'KotlinFunWeb'.");
}
var KotlinFunWeb = function (_, Kotlin) {
  'use strict';
  var appendText = Kotlin.kotlin.dom.appendText_46n0ku$;
  function main(args) {
    var tmp$;
    (tmp$ = document.getElementById('tooltip')) != null ? appendText(tmp$, 'The first step') : null;
  }
  _.main_kand9s$ = main;
  main([]);
  Kotlin.defineModule('KotlinFunWeb', _);
  return _;
}(typeof KotlinFunWeb === 'undefined' ? {} : KotlinFunWeb, kotlin);

The code looks somewhat normal. You could notice that the name of the functions (e.g. _main_kand9s$) are mangled. This means that the original name is transformed and not copied verbatim. This happens because you can overload functions in Kotlin and this is needed to translate them in JavaScript.  This will happen also to the functions that you define, although you can control them with an annotation that we will see later. Also, your code is by default part of a JS module.

If you need to call Kotlin code from JavaScript it is also important to read the documentation for understanding how Kotlin types are translated in JavaScript. There are a couple of important things to notice:

  • There’s no 64 bit integer number in JavaScript, so kotlin.Long is not mapped to any JavaScript object, it depends on a class in the Kotlin runtime library.
  • kotlin.Any is mapped to JavaScript Object
  • kotlin.Array is mapped to JavaScript Array, but Kotlin collections (e.g. List, Map, etc.) depends on a class in the Kotlin runtime library.

In practical terms this means that  if you need to work with JavaScript it may be better to create the data objects with JavaScript and then use it from Kotlin than viceversa.

Copying The D3 Example

Now we are going to copy the aforementioned D3 example.

We have to download d3.v3.min.js (that I renamed in d3.js), uStates.js and include them under the lib directory.

Then we have to add this code to our index.html file.

<svg width="960" height="600" id="statesvg"></svg> <!-- svg to hold the map. -->
<script src="lib/uStates.js"></script> <!-- creates uStates. -->
<script src="lib/d3.js"></script>

This code adds the d3 library, the custom functions to display the USA States and the svg tag that will contain the map. You should also add the style tag and its content (not shown here) from the index.html included in the D3 example.

The file uStates contain the data on the shape of the USA states and a few functions to display a tooltip with temperature data when the mouse hover a state.

Using JavaScript In Kotlin

Replace the main function of our Kotlin code with the following.

fun main(args: Array) {
    js("""
    var sampleData ={};	/* Sample random data. */
	["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
	"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
	"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
	"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
	"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
		.forEach(function(d){
			var low=Math.round(100*Math.random()),
				mid=Math.round(100*Math.random()),
				high=Math.round(100*Math.random());
			sampleData[d]={low:d3.min([low,mid,high]), high:d3.max([low,mid,high]),
					avg:Math.round((low+mid+high)/3), color:d3.interpolate("#0295D5", "#F88909")(low/100)};
		});
    """)

    js("uStates.draw(\"#statesvg\", sampleData, _.tooltipHtmlJs);")

    val d3_kt: dynamic = js("d3.select(self.frameElement)")
    d3_kt.style("height", "600px")
}

Here we can see one way of combining existing JS code in a Kotlin application. We can just reuse some JavaScript code we have, as-is. Just notice that the function js should be used with string constants. Technically you can use compile-time constants. So interpolation with local variables is allowed in the form such as "my name is: ${name}", but only if name is a constant. So in practical terms only string constants works.

It is quite easy to understand what the code does: it generate random temperature data for each state and then it generate the tooltip for each state.

In the first js function we only changed the colors of the d3.interpolate call to match the colors of the Kotlin logo. The function d3.interpolate uses the given colors as the starting and ending points of the scale. Basically the first color is associated with the value 0, while the second one is associated to 1. Any value in between is associated to a color obtained by mixing the two extremes: the lower the value, the closer the color will be to the low extreme, the higher the value, the closer the color will be to the high extreme. Notice also how by using """ we are able to use a multiline string constant.

The first meaningful difference is in the second call to js. This is modified because we ported the original JavaScript function in a Kotlin one called tooltipHtml (we are going to see it later). Since the JavaScript code will be copied verbatim with the rest of our code we do not need to use the full qualified name of our function. It will be inside the JavaScript module generated by the compiler. Instead if you want to use Kotlin code from external JavaScript code you must use the full qualified name, including the name of the module of our project.

The third call to js is peculiar. Actually the call per se is normal, but its result is assigned to a dynamic constant d3_kt. The dynamic keyword switch off the static typing checks and so anything can be used as methods of d3_kt, even non-existing functions (e.g., d3_kt.heatDeathOfTheUniverse("now"). Of course, if you actually call a non-existing function at runtime the call will fail.

On the other hand if the function exist somewhere, for instance is defined in JavaScript libraries, the call will succeed. That is why the following call works as normal. It is important that you choose a valid name for the variable in the JavaScript environment. That is to say that if you pick one that conflict with an existing one in JavaScript, like d3, the code will compile, but it will fail at runtime.

The tooltipHtml Function

The tooltipHtml function receives as arguments the name of the state and the data on the temperatures. With them it generates the HTML that shows the data for the state.

The original function is concise, but also messy. It is a long concatenation of strings that is hard to read and easy to get wrong. The kotlinx.html library instead gives you a type-safe builder that guarantees the proper structure to the HTML code by forcing you to create  valid HTML.

First, we have to import the proper packages for kotlinx.html and traversing the DOM.

import kotlin.browser.*
import org.w3c.dom.*
import kotlinx.html.*
import kotlinx.html.dom.*
import kotlinx.html.js.*

Then we have to define the class that hold the temperature data and the color for a state.

data class Stats(val low: Int, val avg: Int, val high: Int, val color: String)

Finally we can see the code of the function.

@JsName("tooltipHtmlJs")
fun tooltipHtml (name: String, values: Stats) : HTMLDivElement
{
    return document.create.div {
        h4 { +name }
        table {
            tr {
                td { +"Low" }
                td { +values.low.toString() }
            }
            tr {
                td { +"Avg" }
                td { +values.avg.toString() }
            }
            tr {
                td { +"High" }
                td { +values.high.toString() }
            }
            tr {
                td { +"Variability" }
                td { +variability(values) }
            }
        }
    }

    return tooltip
}

The JsName annotation serves to control the name of the generated JavaScript function, which is needed if you want to call it from JavaScript.

As you can see the code is longer, but safer and cleaner. You simply cannot put a tr tag outside a table one, try as you might it will not compile. There are only a couple of things to remember:

  1. The first thing that you have to remember is to make sure that you pass a String where you need it and not an object.
  2. The second one is to prefix the call with the + operator. This is needed because Kotlin transform the + in a call to the unaryPlus function defined by the library. That function add the argument to the children nodes of the current node.

So this works by relying on smart conventions and good functional support. Which means that you can also create a similar library in Kotlin.

Remember that the table, td,  etc.  are nothing more than functions that accepts a lambda as one of their arguments. And according to the convention of the language you can put the lambda out of the parentheses if it is last argument and omit the parentheses if the lambda is the only argument.

The last thing to see is the variability column that we added. It display the results of the call of a variability function that we are going to see now.

The Power Of When

The variability function relies on the when expression to do most of the work and returning the appropriate String.

fun variability(state: Stats) : String
{
    return when(state.high - state.low)
    {
        in 1 .. 20 -> "Low"
        in 21 .. 50 -> "Medium"
        else -> "High"
    }
}

You can think of this expression as a smart swich statement. A traditional switch does not support complex branch conditions, but only constants value. Instead when does support arbitrary branch conditions and more.

Our example here shows how to use a range as a branch condition and return a corresponding String. The else branch is the equivalent of default and can be excluded only if the compiler thinks that all cases are covered by the defined branches. This happen, for instance, if the argument of when is a boolean expression and you include a true and a false branch.

It also important to remember that you cannot activate a cascade of branches omitting the break statement. That is because there is no break statement at all, the first matching branch is chosen and nothing else is checked. Though you can make sure that more conditions activate the same branch combining the conditions separated with a comma (e.g. in 1 .. 20, in 51 .. 60 )

When can be used as an expression or as a statement.

Adding The JavaScript Library

Before building the project now we have to include the JavaScript code for the kotlin.html library in the index.html file. Just makes sure to include it before your generated JavaScript code and after the standard runtime library.

<script type="text/javascript" src="out/production/kotlinfunweb/lib/kotlin.js"></script>
<script type="text/javascript" src="out/production/kotlinfunweb/lib/kotlinx-html-js.js"></script>
<script type="text/javascript" src="out/production/kotlinfunweb/kotlinfunweb.js"></script>

Once you build the project the result should look like this image.

A tooltip over a map showing the USA States

The Last Touches

The final code that you can see in repository also adds a table. We add a few styles, a call to a new function drawTable inside the main function and of course the mentioned new function and another one called drawTable. The code it is not complex, and you can see fully in the repository. Here we are only going to see a few interesting tidbits.

fun drawTable(tableDiv: HTMLDivElement, data: dynamic)
{
    val states = js("Object.keys(data);")
    states.sort()

    [..]

    for(i in 1 .. 50)
    {
        var tr = document.create.tr {
            td { +states[i].toString()}
            td { +data[states[i]].low.toString()}
            td { +data[states[i]].avg.toString()}
            td { +data[states[i]].high.toString()}
            td(classes = styleTable(data[states[i]])) { +variability(data[states[i]])}
        }

        table.appendChild(tr)
    }

   [..]

The data argument is a JavaScript object passed using js("sampleData") and the first thing we do is using a JavaScript reflection function to access the elements of the JavaScript object. While using the js function can be cumbersome for long pieces of code it is also nice and easy for such small things.

Inside the for cycle we can see how to add CSS classes to the HTML generated with kotlinx.html. We also call the styleTable function.

fun styleTable(state: Stats) = when
{
    (state.high - state.low < 33) && (state.avg < 33) -> "low"  // always cold
    (state.high - state.low > 33) && (state.avg > 33) && (state.avg < 66) -> "middle" 
    (state.high - state.low < 33) && (state.avg > 66) -> "high" // always hot

}

As you can see, you can also call the when expression without an argument. In that case the conditions are boolean expressions. That is to say the first branch that is true is executed. In similar situations when is not a replacement for a switch, but for a long chain of if-else. A clearer and more concise alternative.

When a function return the result of an expression you can use a short notation: omit parentheses and use a equal sign (=) instead. These are called single-expression functions in the documentation. You can also omit the return type when the compiler can determine which one it is.

Summary

Kotlin is a great choice for complex web applications if you already know it or if you are using the language for other parts of your application, such as the backend. It allows you to reuse either your competencies or the code, avoiding to duplicate the effort to write the same logic on both sides. It permits to write applications in a more efficient, productive and safe code compared to using pure JavaScript.

If this is not the case, and you are not using Kotlin anywhere else Kotlin could not be your best choice. In that case you might be better served with TypeScript. Kotlin for JavaScript is certainly not bad, actually we think that the Kotlin language is superior to TypeScript. But TypeScript is probably more widespread in that environment and it can be more easily integrated in a typical JavaScript or node.js workflow. Furthermore it can be easily used with the kind of lightweight IDEs that JavaScript developer are used to, like Visual Studio Code.

In our previous comparison between Kotlin and Scala, we said that one of the strong points of Kotlin is that it can be quickly learned by Java developers. Here the situation is reversed: TypeScript is more closely related to JavaScript, which means that it can be quickly learned by experienced JavaScript developers.

Why Kotlin Is The Best Language For Android Development

Why Kotlin Is The Best Language For Android Development

Kotlin is the first language officially supported by the Google for Android development other than Java itself. This alone is a significant accomplishment and a clue that Kotlin is a good language for Android. Another good sign is the reception of Android developers themselves to the announcement.

In this article we are going to explain the reasons why Kotlin is particularly good for Android development looking at two different aspects:

  1. we describe the features of Kotlin which are particularly relevant for Android development
  2. we look at the ecosystem around the language itself: things such as the IDE and the JVM on Android

Considering all of this, there is only one possible reason for not using Kotlin in new Android projects: you do not know the language. Do not worry, we can help you learning Kotlin.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


Language Features And Libraries

Applications for Android have some specific common features, typical of applications with a graphical UI. For instance, they make heavy use of asynchronous calls. Kotlin offers good support for them and even one or two libraries that can help when the language itself cannot.

Deep Interoperability

In a previous article we have talked about the great interoperability between Java and Kotlin which allows a smooth transition between the two or even a peaceful and productive co-existence. This interoperability involve all aspects: from the language itself to the bytecode produced. Something which is fundamental to allow reuse of important libraries that analyze it.

When it comes to the language itself you can find on the Kotlin documentation a complete list of the features for Java support. This interoperability is smart and deep. For instance Kotlin also support some conventions of Java development, as the following example based on getters and setters from the documentation.

import java.util.Calendar

fun calendarDemo() {
    val calendar = Calendar.getInstance()
    if (calendar.firstDayOfWeek == Calendar.SUNDAY) {  // call getFirstDayOfWeek()
        calendar.firstDayOfWeek = Calendar.MONDAY       // call setFirstDayOfWeek()
    }
}

This is great for Android development because the SDKs are obviously still made for Java. Thus by having such a great interoperability you can still write productive Kotlin code when you must use Java libraries.

Function Arguments

In Kotlin function arguments can be named and have default values. This simplifies reading and understanding at the call site and allows to limit the number of function overloads. Because you do not have to make a new function for every argument that is optional, you just put a default value on the definition.

Let’s compare definitions in Java and Kotlin.

 // Java
void drawText(int x, int y, int size, int spacing, String text)
{ [..] }

// Kotlin
fun drawText(x: Int = 0, y: Int = 0, size: Int = 20, spacing: Int = 0, String: text)
{ [..] }

And calling the same function in Java and Kotlin.

// Java
drawText(50, 200, 20, "hello");

// Kotlin
// using default values
drawText("kneel in front of the Kotlin master!")

// using named arguments
drawText(10, 25, size = 20, spacing = 5, "hello")

Nullable Types

In Kotlin you need to explicitly say that a variable can have a null value. By default it cannot. And this allows you app to avoid the common and dreaded NullPointerException at runtime, because most mistakes are caught by the compiler at compilation time. Null references are so risky that the creator of the first language with null reference call it the Billion Dollar Mistake.

var text: String = null // it does not compile
var unsafeText: String? = null // ok 

Kotlin takes advantage of the nullability or, at the opposite, the safeness of types at all levels. For instance, it is taken into consideration during checks.

unsafeText.length // it does not compile

if (unsafeText != null) {
  unsafeText.length // it works, but it is not the best way
}

After you have checked that a nullable type is currently not null you can use the variable in the same way as it is were not nullable, because inside the block it is safe to use. Of course this also looks cumbersome, but there is a better, suggested way, that is equivalent, but more concise.

unsafeText?.length // it works

The safe call operator (?.) guarantees that the variable will be accessed only if unsafeText it is not null.

Nullable types are particularly useful in Android because null is widely used. This can lead to a lot of bugs, but in Java you have not alternatives. Even looking at the official APIs you can see the @NotNull annotation all over the place.

In fact null it is used for several reasons, from performance to the lifecycle of the application that might require certain steps to be executed before you can properly initialize a variable. In such cases you might think that you cannot avoid using null, but you would be wrong. There are several ways to do it, including using late initialization or lazy initialization.

Lazy And Late Initialization

Late initialization works only for variable properties inside the body of a class. The variable cannot be of a null type. You add the modifier lateinit and then inside a method you initialize the variable. If you access the variable before initializing it you get a special exception that clearly indicate what you did wrong. The modifier lateinit was introduced to support dependency injection, but it can be useful in many other scenarios.

If you need a costant value instead you can use the lazy() function to delegate initialization to a function. Lazy accepts a lambda that is executed the first time the variable it is accessed. The function initialize the variable and return its value. The following times the variable is accessed the function is not executed, only the value is returned.

val computedValue: String by lazy {
    println("I am executed only the first time!")
    "A Value That Will Be Subsequently Remembered"
}

Lazy is useful when the computation of the value is costly and it does not change.

Data Classes

You need to use classes to group together semantically connected variables. In an Android app they are frequently used to represent the model of the application. The class just need to hold values, but typically you need a few standard methods to manage the data, getting and setting values of properties, etc. And you also have to update them every time you change the data.

Kotlin gives all that you need automatically, simply by using the data keyword in front of the class definition.

data class User(val name: String, var password: String, val age: Int)

That’s it. Now you get for free:

  • getters and setters (these only for variable references) to read and write all properties
  • component1() .. componentN() for all properties in the order of their declaration. These are used for destructuring declarations.
  • equals(), hashCode() and copy() to manage objects (ie. compare and copy them)
  • toString() to output an object in the human readable form Name_of_the_class(Name_of_the_variable=Value_of_the_variable, [..])"

For example, given the previous data class User

val john = User("john","secret!Shhh!", 20)
 
println(john.component1()) // it prints "john"
// mostly used automagically in destructuring declaration like this one
val (name, password, age) = john
println(age) // it prints 20

println(john) // it prints "User(name=john, password=secret!Shhh!, age=20)"

Is it mind blowing? No.

Is it a very useful thing? Yes, it is. It saves time and it allows easier changes to the model of an Android application, since you do not need to write custom functions to compare objects yourself.

Eliminating Utility Classes

Android applications need utility classes to add new features on existing classes or perform common operations specific to the app. Kotlin offers a couple of way to get rid of them: extensions methods and the possibility of using top-level functions without defining a class.

It is important to remember that both are syntactic sugar. Using extensions methods to extend a class you cannot access private or protected members of that class.

// extension method
fun String.bePolite() : String {
  return this + ", please"
}

val ask = "Pass me the salt"
println(ask.bePolite()) // It prints "Pass me the salt, please"

And if you want to use top-level functions in Java they still are inside a generated class. The generated class name usually is based on the name of the file in which the extension method is defined, but this can be altered with annotations.

// filename polite.kt
package strings

fun checkPolite(request: String) : Boolean {
    if (request.contains("please"))
    	return true
    else
    	return false
}

// a Java file
import strings.PoliteKt;

PoliteKt.checkPolite("prove P=NP, please");

There is another feature that makes utility methods more useful: operator overloading. You cannot define custom operators, but you can very easily use standard operators for your classes. All you have to do is defining functions with specific name and then Kotlin will translate the corresponding operator in this function on the call site. For instance if you define a function plus() for your class Kotlin will translate objectOfYourClass1 + objectOfYourClass2 in objectOfYourClass1.plus(objectOfYourClass2).

Functional Features

Functional programming is not a new programming paradigm, but its success it is relatively new. This is due to the increase of situations that require a lot of concurrency and parallelism. Android applications are not the best use case for fully functional applications, but they need to use asynchronous calls for UI interactions and often to call online backend services, so they would benefit from functional features. In short, Android applications benefit from functional features in the context of imperative programming.

The most common features are higher-order functions and lambdas. Higher-order functions are functions that accept functions as arguments or return one. Lambdas are anonymous functions that can be passed around. The problem is that only with version 8 that Java started including them, so many are forced to use a library, like Retrolambda. The reason because you cannot use Java 8 is explained in the later paragraph The Java Platform On Android. This is far from ideal, because the language itself does not support them and thus many libraries cannot take advantage of them.

A language like Kotlin, that include them from the beginning, allows you to take full advantage of them.

We assume that you already know the advantages of similar functional features, so what we are going to show is an example of how well and easily you can use them in Kotlin thanks to many of its conventions.

val strings: List = listOf("one", "two", "three", "Hello", "to", "Kotlin", "and", "Me")
// we first take only the strings longer than 3
// then we transform each string in its lowercase version
// finally we join them in one string
println(strings.filter { it.length > 3 }.map { it.toLowerCase() }.joinToString())
// it prints "three, hello, kotlin"

If you familiar with C# you will notice how similar this is to LINQ. This is also noted in the official documentation. And it goes to show how pragmatic Kotlin is. Kotlin took the best out of many languages and it added some more. In this case some more is the default name it that can be used when the lambda takes one argument. It is also the chance to put the lambda out of the parentheses if it is the last argument of the function and to omit the parentheses altogether if a lambda is the only argument (eg. for filter and map).

Concise, readable and easy to use. What could you ask more?

Kotlin Android Extensions

There are also Kotlin Android Extensions that allows you, among other things, to replace the annoying and bug-ridden findViewById() calls with synthetic properties. An example to clarify, from the documentation:

// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView.setText("Hello, world!") // Instead of findViewById(R.id.textView) as TextView
    }
}

There are some libraries for Java that allows you to do something similar, but they usually requires annotations. Kotlin offers a simpler way to do it, without any extra code or runtime.

Anko

Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java.

Anko is a popular library that simplifies Android development with a lot of helpers. In fact, they are too many to mention all of them here. But we can say that the library is divided in several parts:

  • Anko Commons: full of helpers for intents, dialogs and toasts, logging, resouces and dimensions…
  • Anko Layouts: a fast and type-safe way to write dynamic Android layouts
  • Anko SQLite: a query component and parser collection for Android SQLite

We are going to show an example of Anko Layouts, because it also show another useful characteristic of Kotlin: type-safe builders. These are a safer and more concise alternative to configuration files and such things to describe data with a hierarchical structure. A typical example is a XML file used to describe a UI.

Using an XML file requires you to rewrite each time for each interface the same boilerplate structure. The only thing that varies is the data itself. This is not just boring, but also error-prone, hard to read and unsafe. Because it is easy to commit a mistake. Builders in Kotlin provide a better alternative.

You can transform the following Kotlin code (and let’s not even talk about the corresponding Java version…)

val act = this
val layout = LinearLayout(act)
layout.orientation = LinearLayout.VERTICAL
val name = EditText(act)
val button = Button(act)
button.text = "Say Hello"
button.setOnClickListener {
    Toast.makeText(act, "Hello, ${name.text}!", Toast.LENGTH_SHORT).show()
}
layout.addView(name)
layout.addView(button)

…in this much better version…

verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}

Which creates the following interface.

Example Layout defined with Anko

Example Layout from the Anko documentation

There is even an Android Studio/Intellij IDEA plugin to preview interfaces created with Anko.

Building Kotlin Applications For Android

There are some technical aspects to consider when building Kotlin applications for Android. They are relative both to Java and the tools used to develop for Android and involve many concerns of developers other than the language itself.

The Java Platform On Android

A table and a graph representing the percentages of devices for each different version of Android

Data on the different versions of Android coming from the official documentation

Experienced Android developers will already know that the history of Java on Android is complicated. For the rest, here there is a short summary. When Android launched there was not an open-source, stable and mature version of Java, since OpenJDK was just starting. So Android was based on a modified version of Apache Harmony. But with the maturing of OpenJDK the support of companies, like IBM, for Apache Harmony diminished.

Apache Harmony supported 97% of Java 6, but the project was ended in 2010, leaving Google to support the whole codebase, both its custom part and the open-source foundation. Furthermore Oracle sued Google also because it claimed Android fractured the Java platform. So Google switched the basis of Android from Apache Harmony to OpenJDK with Android 7, which also gave Android a new higher-quality foundation.

This means that, at the moment, most of Android devices support Java 6, while the last version of Android, and the future ones, should support the latest Java version. Although one problem is that there is still a delay between the OpenJDK and Android Java support because Google must adapt OpenJDK to its custom parts.

Given that the Kotlin compiler produce bytecode compatible for Java 6, Kotlin can safely brings its features to the majority of Android devices now. Thus it is the only practical choice for a modern and productive programming language for most Android developers.

IDE And Tool Support

The official IDE supported by Google for developing Android applications is Android Studio. This is the IDE that replaced the previous one based on Eclipse and it based on the open-source (community) version of IntelliJ IDEA. IntelliJ IDEA is developed by JetBrains itself and obviously supports Kotlin. But Android Studio will natively supports Kotlin starting from version 3, currently in pre-release status. There is a Kotlin plugin for previous Android Studio versions, too.

This is part of the official support of Kotlin for Android development. But it is not the only thing. We have already seen libraries and extensions made by JetBrains for Android.

Android Studio uses Gradle for build automation and Kotlin can be used as a language for Gradle scripting.

Finally, the Android SDK supports ProGuard, a tool to optimize, remove unused methods and obfuscate Java bytecode. Given the similarity between Kotlin and Java bytecode ProGuard also works well for Kotlin. This is a good example of how deep goes the effort of JetBrains to maintain compatibility between Java and Kotlin and why they do that.

APK Limitations

Apart from Java support there are many small differences between the official JVM and the one supported by Android. One that matters particularly for Android development is the limit on the numbers of methods and fields in your application: 216, which means a bit more than 65000. The Kotlin runtime and standard library combined adds around 7000 methods, which is circa 10% of your method count. This is not an insignificant amount, but using ProGuard it can be reduced substantially, even to 42!

Furthermore it can actually be an advantage if it allows you to get rid of an alternative library. Good candidates are libraries that introduce small functional features or improve the productivity of developers, or the quality of life. The developers of App Lock managed to reduce the total method count by 10% and the total lines of code by 30% with a conversion from Java. Another app developer reached a reduction of 20% lines of code.

Also, to put things in perspective, 7000 methods are not that much compared to the ones of a library like Google Guava, that has almost 15000 methods. And let’s not even talk about the numbers of languages like the 50000 of Scala or the 30000 of Groovy. Such high numbers make them practically unusable for Android development, no matter the advantages.

There is also a limit on the size of the APK that you can upload on the Google Play Store. This limit is 100MB. Even without that artificial limit there would also to consider the limited space on the users devices and possibly the costs of transferring the APK over metered connections. So the fact that Kotlin adds only around 1MB to the debug APK, and even less to the release one, it is a good thing.

Bottom line: using Kotlin have consequences in light of APK limitations, but considering the alternatives it is a no-brainer.

Java Conversion Tool

JetBrains has done a solid job with their Kotlin plugin and its ability to auto convert Java to Kotlin. It can get your class 60–70% of the way there, leaving you with some tuning and idiomatic/stylistic things to take care of.

How we made Basecamp 3’s Android app 100% Kotlin

JetBrains developed a tool to convert Java code in Kotlin. This is a tool that can be accessed in many ways, in the online test environment, which make it useful for learning, and in the IDEs, like IntelliJ IDEA and Android Studio, which make it useful for learning and coding.

It is a very useful tool, but as most automatic conversion tools it is not perfect. Studying the results is needed for learners to understand the basics use. While it may not break your class, it does not always produce the best code, so it is also useful to study the results to modify them in the idiomatic and suggested way of using Kotlin.

Compilation Speed

The time necessary to compile Android application has been a pain point even with Java for some time, since the adoption of Gradle. With Kotlin the speed is now great, even for people that during the beta criticize it for its slowness. It is even better than Java with Retrolambda.

What does it mean great? On clean builds a Kotlin application it is slower than a Java one by around 15%. This remain true both for the first build and for subsequent builds with the Gradle daemon. But where it counts, that is to say during development when you change a few files at once before recompiling (incremental builds) it is actually faster than Java itself.

Drawbacks

The language Kotlin is already mature, but there is still work to do in the ecosytem around the language.

Annotation Support

Some advanced features like Java annotation support and reflection were not greatly supported in Kotlin up until the last few pre-release versions. A frequently requested feature used to be support for annotation processing in Kotlin. In particular many people wanted support for ButterKnife, the famous Android library that uses annotation to bind field and methods with views. There were already alternative to do the same things of ButterKnife with Kotlin, but good annotation support was needed.

Now stability and support is there, but there are still difficulties in some cases, if nothing else from configuration and changing apt with kapt. Kapt is the annotation processing tool for Kotlin that brings support for dagger, a fast dependency injector for Android, and dbflow, an ORM android database library that writes database code for you. At the moment using kapt noticeably slow compilation speed. The Kotlin ecosystem is mostly there, but there are still annoying problems to fix.

Analysis Of The Code

One way that Kotlin managed to be so well compatible with Java, and with so little overhead, is that a lot of the smart stuff of Kotlin is in the compiler and not the generated bytecode. Which means that reflection is costly and requires a specific library in addition to the runtime. You need to add kotlin-reflect which adds almost 20.000 methods to you app which is clearly very far from ideal. The workaround is to use reflection in Java or use the Java reflection support in Kotlin. For instance you can use String::class.java.methods to access the Java/JVM methods created by the Kotlin compiler.

The first option requires you to keep using Java, at least in some places, but it is guaranteed to work. The second one allows you to use exclusively Kotlin, but the results may be different from what you expect. That is because the productivity granted by Kotlin relies on operations behind the scenes. For example to allow you to use default values in Kotlin the compiler generates a Java method for every combination of arguments.

Another current problem is the lack of static analysis tools for Kotlin. It is true that the Kotlin compiler is smarter and safer than the Java one. And you can actually integrate the command line compiler in your workflow. Still this is undeniably a current weakness of Kotlin, which probably will remain for some time given that the official Kotlin parser is open-source, but tightly integrated in the compiler. Thus it is not easy to extract and reuse it.

Is Kotlin The Swift Of Android?

Kotlin and Swift logos

Kotlin and Swift started being developed roughly at the same time, but Swift was released first. So there is a certain reputation of Kotlin as The Swift Of Android. This is not so much because one inspired the other, but because both of them were developed to bring a more modern programming language to their respective operating systems. They intend to be an upgrade to their predecessors.

In that sense the languages have similar needs of keeping compatibility. At the very least, they need to keep it at the design level because they target the same environments and they surely target the same developers. They largely succeeded. And being languages developed at the same time they have also similar concerns and features, for instance they are both languages in which type inference, nullability and constant values are concerns.

So you could say that Kotlin, at least for Android, is like Swift for iOS. This is a good thing because it simplifies development and understanding. You might not have the same developer working on both the Android and iOS version of one app, but having similar languages makes easy for both teams to coordinate between them and follow the same structure. This increase productivity and reduces the risks of different bugs introduced in different versions of the same app.

Kotlin Is Better Than Swift

One important difference, though, is that, as usually happens, tools and language design of Apple is a bit of lower quality than the alternatives. This happens because Apple has really no competition in the development part. If your customers choose Apple you, the developer, have really no choice, you must work with what Apple gives you.

In fact a common criticism is the instability of Xcode, compared to Android Studio. Also Swift development may have been too quick: there have been already three versions of Swift in three years and each version introduced breaking changes. While it is better to have an updated language than a stale one, a language that moves too quickly it is also not ideal for developer productivity.

So we would say that Kotlin for Android is better than Swift for iOS: it has better tool support and it is a more stable language.

Summary

Kotlin is a language designed to be easy to use and extremely productive. It brings to the Java world many of the modern features that it lacks and it adds some new ones that fits the style and needs of experienced Java developers. It does the same for Android development and on top of that adds libraries and tools to simplify common development patterns for the mobile OS.

It is not an accident that Kotlin is loved by Android developers and officially supported by Google. It works great and it is the best programming language for Android development that you can use right now.

JetBrains started focusing on supporting Android developers and got great popularity among them. Now it can use that traction to challenge Java in other areas. However every Android developer can now benefit from those investments and enjoy the results.

What are you waiting for? What is your reason for not using Kotlin for Android development?

Kotlin vs Scala: Which Problems Do They Solve?

Kotlin vs Scala: Which Problems Do They Solve?

Scala and Kotlin are the two contenders for the Java throne. At the very least they are the two main languages to consider using in a JVM based application.

They aim to solve the same problem: providing a better Java but they do it in a very different way:

  1. Scala has been designed in the Academia, Kotlin in a leading software company. The background in which they are born explain most of their differences. Scala has been born to try some cool ideas on functional programming and mixing different paradigm. Kotlin is about solving practical problems. Kotlin designers cared about compilation times and great tool support, because those things matter to programmers, even if they do not sound exciting for other language designers.
  2. A great merit of Scala is that it proved to be possible to build another major static language for the JVM. It made clear that the JVM was flexible enough to allow language designers to benefit from it. Kotlin arrived much later. At that time people were not excited by the idea of having a new JVM language, they started caring about the practical aspects.

In this article we are going to compare Kotlin and Scala mostly for their uses, not their technical features. We are just going to make a general overview of the features of these two languages, and we are mostly concentrating on what they are designed for.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


Is There Anything Wrong With Java?

Both Kotlin and Scala runs on the JVM and compare themselves to Java. This begs the question: is there anything wrong with Java?

Well, certainly Java did a lot of things right. It was an evolutionary language, rather than a revolutionary one. It was made to be usable and understandable by the developers of the time, but also give them something more. Its promise: Write once, run anywhere is alluring now as it was at the time.

In fact Java is probably the most used programming language in the world. Java is also arguably the most used language in the enterprise world and the most widely taught language in computer science courses.

So Java is great, just like C is great. But just like C, Java is old.

And although Java has evolved more than C, and luckily in a more organized way that C++, it is lagging behind many other languages. It is still certainly good enough for daily use. And many developers are happy with Java. But many compare it unfavorably with C#, which is a language with similar purposes. Or really almost any other modern language.

It is not a secret that many developers, and companies, want something more productive and I dare say fun to use. There is a lot of technical criticism of Java itself and a lot of baggage in the language which limits what it can be made easy to use. This is the curse of success: so many people use it that the designers cannot really change the fundamentals even if they had discovered they were wrong about something.

Why Scala And Kotlin

Scuola di Atene a painting of Raphael

For many years developers have built new languages on the JVM. Many of these languages attempted to be a mix of improvements over Java and offering something more than Java. That is to say many tried to improve the developers productivity and experience, while doing the same things that you can do with Java and/or also tried to make something different, like a dynamic language or one similar to Lisp.

Scala stands for Scalable Language, a language designed to scale with the needs of its users, while Kotlin is the name of an island, just like Java.

We picked Kotlin and Scala because they are both quite popular, statically typed languages and good representatives of two approaches: Kotlin is purposefully made as an improvement over Java while Scala is a different language altogether. Kotlin gives you everything you need, Scala gives you everything you may want.

Scala has the right features, but its most obvious deficiency is very slow compilation

You can already find articles of people that decided to move from Scala to Kotlin. In some ways the creators of Kotlin did that too. In fact, the  quote comes from an interview with the lead Kotlin developer that explained one of the reasons because they decided to create Kotlin. The other one, of course, was to create a better language than Java, but that was still compatible with the JVM.

This does not necessarily mean than Kotlin is better than Scala, of course. On the contrary it means that Kotlin designers think that Scala is a good language. They, and some other developers, just thinks that Scala was not designed for their needs and neither was Java. So they made Kotlin.

A Comparison Of A Few Features

As we said in the introduction we are not listing all the technical features, nor we are looking at the syntax. We think that too much details can be confusing especially without a context. Furthermore nobody choose a language with a checklist. Nevertheless it is important to  see some significant features and the approach the languages pick.

Object-oriented

Java is a language designed for object-oriented programming, but not everything is an object. The basic types, like numbers, are represented as primitive types. In Scala and Kotlin everything is an object and can be accessed as such. This is not necessarily a deliberate choice, since there is a slight penalty for using reference types instead of primitive, but it is due to the fact that in JVM you cannot define value types. So to get the advantages of a smarter type systems you can only implement it with reference types.

Scala and Kotlin supports also other programming paradigms. Although Kotlin remain mainly an object-oriented language it include basic aspects from all programming paradigms that are advantageous in daily programming.

Functional Programming

Kotlin supports fundamental functional features, such as lambdas and higher order functions. But it does not fully support functional programming paradigm. As always, it goes for the pragmatic bits that can be useful to the average programmer, without requiring a PhD in Computer Science to be used proficiently. For example:

  • independent (top-level) functions are fine and you do not need to make utility classes to contain disparate functions
  • Kotlin defines expressions rather than statements, so you can assign to variables things like the result of if
  • you can easily define immutable data with val, instead of var. No need for modifiers like final

Scala supports equally well the functional and object-oriented programming paradigms. It was designed with this goal in mind, and it has most features that you will find in Haskell, but not in Kotlin or Java, such as currying, memoization, partial application, type classes… It has the whole package, so to speak.

Small Things

Every language can be different. Both Kotlin and Scala have many productivity features that are standard in new languages, but they were not so when Java was created, things like type inference and quick ways to create a singleton or a data class.

Kotlin

Given the focus of the language, Kotlin has all the essentials and little else, although it also has first-rate support for null-safety and interesting things like smart casts. Smart casts means that if you check the type of a variable that is automatically casted to the new type, of course if it actually is a variable of that type. Generally speaking Kotlin uses very well its set of features, rather then adding more things. For example you can overload operators, but only the basic operators that are already in the language, you cannot define new ones.

Kotlin also ease the creation of an internal DSLs, or fluent interface. It does that with lambdas and the help of some syntactic sugar. Like the fact that the last argument of a function, if it is a lambda, can also be put outside of the parentheses. This is useful to reduce the need for complex string interpolations. For instance, this example uses a library to create HTML.

createHTML().table {
    for (language in languages) {
       tr {
           td { +language.name }
           td { +language.popularity }
       }
    }
}

Scala

Scala instead has all you may want from a language that need to be both functional and object-oriented. Although it has some small flaws of its own, for instance, the managament of null-safety is less efficient and natural than in Kotlin.

Scala also excels in the creation of complex internal DSLs, by including  macros and the chance of creating custom operators. Using Scala you have great freedom and many chances of hang yourself. For example, many developers lament the overuse of arcane custom operators whose purpose is not really clear from the code itself.

It only a slight hyperbole to say that if you imagine any construct you can do it in Scala. So you have to pay attention to the imagination of your developers, and their competence.

Interoperability With Java

People working together

Kotlin Was Designed To Work With Java

Kotlin is a language created to maintain compatibility with Java. It even has functionalities to facilitate interoperability with Java, like making easier to call Kotlin idiomatic code from Java. So you can keep developing legacy software with Java, but creating new ones with Kotlin.

One reason because Kotlin is so popular on Android it is due to its compatiblity with Java 6, which is largely the current Java version of Android. So Kotlin brings some features that are already in Java 8, but are not available to Android developers.

Interoperability with Java is not an accident, or simply what you can get by using a language that runs on the JVM. JetBrains designed Kotlin aware of the current Java ecosystem and situation. They tried to bring the most value in the way that was easier to use. This compatibility get down to the structure of the bytecode itself. And was one of the reasons that lead Corda to pick Kotlin over Scala.

Scala Can Work With Java

Scala was created to run on the JVM platform, for easier deployment, but compatibility was not really a primary objective. This starts with the technical side and keep going with the language features. For instance the recent versions of Scala requires Java 8.

This, coupled with the features of the language, means that if you want to develop with Scala going back-and-forth to Java is hard and not really an intended use case. Working with an existing Java codebase? Yes, you can. Keeping developing Java software with Scala? Not really a good idea.

Compatibility is also made difficult by the fact that Scala support functional programming as well as objected-oriented programming. If you use its advanced functional features you cannot really do much with that in Java. And, even if you could, your Java programmers might not know how to use them.

Different Philosophies

Many successful languages have precise objectives and a specific philosophy of what programming should be. Kotlin and Scala are no different. Kotlin wants to be a better Java, while Scala plans to be much more than Java.

Kotlin Is A Better Java

You could argue that Kotlin has fulfilled its original objective: it became the first language to be officially supported for Android development, other than Java. This is undeniably a great achievement that prove a couple of things: the Java community loves Kotlin and it is easy to introduce Kotlin to Java developers.

Kotlin is a pragmatic language designed to improve productivity and being easy to learn for Java developers. It is mainly designed to be Java like, but with a bit of C# and even Scala, on top of the Java model. It adds features that Java programmers want, like lambda and basic functional features, and simplify life, like smart casting and non-nullable types. Kotlin additions in many cases are what is usually called syntactic sugar. A more concise way to express common patterns used by developers.

While Kotlin offers some support for functional programming it really does it to accomplish easier procedural or imperative programming. For instance, individual functions can now be first class citizens of the language. Kotlin prefers to be simple rather than being formal.

Scala Is More Powerful Than Java

Scala never tried to do any of that that. It was designed to be more powerful than Java. Or more generally, a better language than Java. Scala was designed to do things that Java could not.

Scala offers great support for advanced functional programming, in fact functional programming is a first-class citizen just like object oriented programming. This adds complexity and make Scala a famously hard language to learn and use. This is not strictly a flaw of the language, you can do more, so there is more to learn. You can mix paradigms and thus you must know them all.

This can be an advantage in the rights hands and a disadvantage in the wrong ones. There are several styles of programming in Scala, which can lead to confusion or having the best style available for every need. In any case this lead to higher costs of development and higher wages for good Scala developers. Which can be a good or a bad thing depending on who you are.

The World Around The Languages

A representation of Earth half in daylight and half in the dark

Community

Scala has a larger community, if nothing else because it has been around longer. Unless we are talking about Android development where Kotlin probably has already the upper hand. Just look at the 2017 Google I/O to see the enthusiasm with which Kotlin was received.

The relative lack of native libraries is somewhat mitigated by the excellent Java compatibility. But robust libraries with idiomatic Kotlin code are not always available in Kotlin or they are not as deeply developed as the ones for Scala and Java.

Documentation And Easy Of Learning

Both languages have a good documentation, but surprisingly the Scala longevity might be a problem here, because some parts “are in state of flux” (for example the Scala Wiki) or might be outdated now that the official Scala website has been updated. Furthermore you must train developers in Scala and train them in your style of development. You cannot just pick some Java developers and give them a few days of training. Actually, if you pick a typical Java developer you might even have to train him in functional programming.

You can do that with Kotlin. Corda actually did just that:

Excellent documentation and tiny standard library makes it a very fast language to learn. We do not explicitly advertise our positions as needing Kotlin experience and have been hiring people who didn’t know it already, with ramp-up times in the range of 1-3 days before the new team member is producing idiomatic code.

Kotlin is easier to learn and easier to try, it has a great online test environment with examples and which can even convert Java code. So you can instantly see how to do the same stuff you do in Java.

Tooling

Both Scala and Kotlin are statically typed languages which allows a whole class of compiler checks and static analysis tools. So the potential is similar. Having said that, tooling is better for Kotlin, which is unsurprising given that is created by JetBrains, the famous software house of programming tools. As for the documentation, it is not really a case of Scala is bad, but Kotlin is awesome.

Previously the official Scala website offer an Eclipse-based IDE. We reported this fact and that is why you are going to see mentions about it in the comment. Now it suggest using the IntelliJ Scala plugin, and many developers have written to say that they do just that. So there is a good IDE for Scala.

However Kotlin is already integrated in IntelliJ IDEA and Android Studio. It also has a plugin for Eclipse. Furthermore IntelliJ IDEA has also the same conversion tool and examples available online, so you can easily convert Java classes and learn the language with interactive examples. You can also use a standalone compiler if you need a more advanced integration with your workflow.

Summary

Kotlin design seems to take an holistic approach: its authors considered how each design decision affected the whole development experience. Was a feature really necessary or were there alternatives? Would that choice make the compiler slower? Would it make more difficult to provide good tool support?

Scala designers seem not to bothered by pragmatism, as they follow another great idea. Scala reminds me of C++: there is always place for one more feature. Sure, they say that you can adopt your own subset and reduce the complexity of the language as it is used in your organization. It could work in some places, but I am not sold to the idea for everybody.

Many people moved to Scala with hope for a better language and unsatisfaction with Java. Most of the people that had the first motivation are happy with Scala. Many of the ones that were simply unsatisfied with Java are a bit perplexed by the complexity of Scala. It is not the right language for them. It is simply something different from plain old Java.

Kotlin is probably a better language for them. Every Java developer can easily pick Kotlin, not so for Scala.

If you need a Java-like language that is more productive than Java itself, you should go with Kotlin. If you need Haskell plus Java, you should go with Scala.

We hope that this pragmatic comparison has been useful. But if you want to get a more technical comparison and a look at the syntaxes of the two languages we suggest you look at Scala vs Kotlin, or a series of three articles by A Java geek.

100+ Resources To Learn Kotlin The Right Way