Kotlin for Android: new project

For this tutorial, I’m going to walk you through a sample project that gets you set up for development in Kotlin for Android, using Android Studio and the Kotlin plugin.

Create a new project

As you would normally do with a Java-based Android application, create a new project in Android Studio by choosing ‘Start a new Android Studio project’:

Start a new Android Studio application
Start a new Android Studio project

or if you already have a project open, go to ‘File > New Project’:

New Project
File > New Project

Give your project a name.  I gave mine the name ‘FirstKotlin’:

First Kotlin
I named mine ‘FirstKotlin’

Choose the defaults on the next screen.  Mine looked like this:

TargetSettings
Target Android Devices

On the ‘Add an Activity to Mobile’ dialog, choose ‘Basic Activity’:

BasicActivity
BasicActivity

On the ‘Customize the Activity’ screen, just leave the defaults:

CustomizeActivity
CustomizeActivity

Click finish to create the project.

Run the application

After your project is created, go ahead and run it to make sure that you have a working application.

running app
running app

Download Kotlin plugin

Pull up Android Studio preferences (Android Studio > Preferences…).  Go to Plugins in the left navigation, and search for ‘Kotlin’.  Install this plugin.

kotlin plugin
kotlin plugin

Modify application build.gradle to add Kotlin plugin as a dependency

Add classpath org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.6 as a dependency to your application’s root build.gradle file.  My full application build.gradle is below:

 

Modify module build.gradle to apply Kotlin plugin

Add these two lines to your module’s build.gradle.  My module’s build.gradle is found at app/build.gradle:

Full build.gradle is found below:

Convert default MainActivity.java to Kotlin

Now here’s the fun part.  Let’s convert the MainActivity.java file to Kotlin.  Open the MainActivity.java file (mine’s at app/src/main/java/com/devdustin/firstkotlin/MainActivity.java).  Then, go to Code > Convert Java File to Kotlin File:

convert java to kotlin
convert java to kotlin

Your converted class should look something like this:

 

Run the application

Now, run your first Kotlin app!

running app
running app

If you get the same result as from before converting your Java file to Kotlin, good job!

Kotlin vs Java analysis

What differences do you notice between Kotlin and Java?

Here are a few to pay particular attention to:

  • Override as a keyword, not an annotation: in Java, the @Override annotation is used to indicate the developer’s intention in overriding a method, and if not properly overridden, will cause a compile time check. But it’s not required (though you’ll likely get a compiler error, depending on the compiler you’re using).  In Kotlin, you are required to use it.
  • Primary and secondary constructors: shown in the class above only as a primary constructor in ‘AppCompatActivity()‘, Kotlin classes have a unique way of handling object construction.  I’ll dig into this more in future posts.
  • Null Safety: one of the goals of the Kotlin type system is to avoid NullPointerException from occurring.  The ‘?’ after Bundle indicates that savedInstanceState could potentially be null.  You can also expect future posts on this topic, as it’s key to understanding Kotlin.
  • ‘fun’ indicates function: Kotlin uses the ‘fun’ keyword to indicate what would be a method in Java.
  • ‘extends’ and ‘implements’ are represented using a colon: very much like C# and other modern languages.
  • Semicolons are optional: though you can add them if you’d like to.
  • Function parameters are written ‘backwards’ compared to Java: they are defined using Pascal notation: name: type, and are separated using commas. A type is required for each parameter.

Conclusion

In this sample Android project you get a taste of what it’s like to develop with Kotlin. The Kotlin plugin for Android Studio includes a great tool for converting Java files to Kotlin, which helps developers ease into developing with Kotlin.

I went over a few language features that are expressed in this simple example.  Future posts will touch more in depth on these and many other Kotlin topics, with an emphasis on Android development.

What does the ‘which’ command do?

unix
unix

The ‘which’ command is great for finding where a program that exists in the user’s path is located.

To use it, type the following in a terminal:

What prints out on the next line is the first location found where that program is installed.

There are options available, see below:

Genymotion device goes offline after Mac screen locks

Have you ever had your Genymotion device go offline after locking your Mac screen?

After debugging in Android Studio, locking my Macbook Pro screen, and then logging back in, frequently my Genymotion device will show as [OFFLINE] to the Android Studio debugger.  It’s really an inconvenience, as restarting the device and app often take a while.

If so, rather than restart the device  completely, try this from a terminal window:

Give adb a moment to restart, then issue this command:

Once adb has restarted, you’ll see your device listed, like below:

 

 

Note: if you get ‘command not found’ after typing ‘adb’, then it must not be on your PATH.  Add ‘ANDROID_HOME/platform-tools’ to your PATH environment variable.  The location of ‘adb’ on my machine (after typing ‘which adb’) is ‘/Users/dustinkendall/Library/Android/sdk/platform-tools/adb’

Hope this helps!

Kotlin vs Java: performance

How does Kotlin performance compare to Java’s?

One of the questions you’re bound to have when switching over to Kotlin is whether or not it is faster than Java.

While an application’s performance is highly dependent on its OS, runtime, and the actual code, in general Kotlin will perform very similarly to Java.

JetBrain’s kotlin compiler produces JVM bytecode.  While I’m not going to an analysis of the bytecode that it produces, from the research I’ve done it appears that it is very similar (at least in the performance sense) to the bytecode that Java compiles to.

But…

While the question posed in this blog post is definitely a common one, it’s a bit too simplistic.  Much of how an app performs is dependent on the actual code that you write and the algorithms and data structures that you choose to use.

Kotlin has a distinct advantage over Java in this arena, because it provides us with implementations of certain programming patterns.  These patterns are highly efficient and likely to be less buggy than if you were to roll your own.

Take Kotlin Data Classes for example

You get this construct for free in Kotlin.  In order to do the same thing in Java, you have to write all the boilerplate code yourself.   This introduces the potential for that code to be buggy and inefficient.  Not good.

Joshua Bloch’s Effective Java describes the Immutable Object pattern.  Kotlin Data Classes are a great implementation of this pattern.  And you get it for free, built into the language.

Conclusion

Comparing Kotlin’s performance to Java’s is a common question that many have before switching from Java to Kotlin.  Kotlin compiles to JVM bytecode and the bytecode it produces is very similar to Java’s.  There is no reason that Kotlin should be slower than Java when comparing equivalent code.

Comparing speed of languages is less important than the data structures and algorithms used by the developer.  Kotlin provides some great built-in patterns that result in cleaner, easier to read, and less buggy code.

wc word count command

unix
unix

What is the wc command in Unix-like operating systems?

Have you ever had the need to count the words in a text?

If you’re like me, you’ve probably used an online word counting tool, like the one found here.

But who likes copying and pasting to a website when you have such great tooling available via terminal?

Check out the wc command.  Usage: wc [-clmw] [file …]

Here is an example:

See below for more usage options:

Introduction to Kotlin for Android

Kotlin
Kotlin

What is Kotlin?

Kotlin is a programming language that purports to be 100% interoperable with Java. Created by JetBrains — the company that created IntelliJ IDEA, WebStorm, and others. JetBrains released the first version in 2011, reportedly after one year of development. The 1.0 release of the language happened on February 15, 2016.

Kotlin is an Open Source language, developed on Github (https://github.com/JetBrains/kotlin) under the Apache 2.0 Open-source license. As of this post, there are 139 contributors to the project.

Why develop with Kotlin?

  • Safe — for example, null references are controlled by the type system
  • Concise — reduces a lot of boilerplate code
  • Versatile — build Android apps, front-end code, and server-side applications
  • Interoperable — with frameworks and libraries of the JVM
  • Easy to read and learn — less verbose than Java
  • Great tooling — Java-to-Kotlin converter, command-line compiler

Kotlin advantages and features

  • Lambda expressions
  • Extension functions
  • Null-safety
  • Smart casts
  • String templates
  • Properties
  • Primary constructors
  • First-class delegation
  • Type inference for variable and property types
  • Singletons
  • Declaration-site variance and Type projections
  • Range expressions
  • Operator overloading
  • Companion objects
  • Data classes
  • Separate interfaces for read-only and mutable collections

Projects that use Kotlin

https://github.com/Kotlin/anko
https://github.com/antoniolg/Bandhook-Kotlin

Why is Kotlin good for Android development?

Oftentimes in Android you’ll get crashes due to NullPointerException. As null references are controlled by the type system in Kotlin, you are much less likely to come across them.

Less crashes == happier customers == better app ratings.

Jake Wharton has a post that describes some advantages Kotlin brings to the table for Android.

Conclusion

Kotlin is a great new language replacement for Java.  It’s very popular in the Android development community, and can be used for back-end server-side development, as well as front-end development.

Try it out for yourself with the online demo IDE: http://try.kotlinlang.org/