Have you ever had the need to read an external variable like an environment variable from your Android build.gradle file?
On a recent project of mine we needed to enable our QA engineers to specify different login urls (for dev, staging, production, etc) to run our test automation against. The idea is that they would set a specific environment variable, ‘ANDROIDDOMAIN’ in this case, and our build script would read in this variable and add it to the BuildConfig class, which we then reference via our test.
Below is the code that reads in the environment variable:
As you can see, here we look for the environment variable named ‘ANDROIDDOMAIN’, and if it is present we print it out and return it from this method.
The next code snippet shows how to add the result of the ‘getAndroidDomain()’ call to the BuildConfig class (in this case we add to the BuildConfig debug class:
Now in our test class we can access the ‘TEST_ANDROID_DOMAIN‘ field on this class, like so:
Do you have a better way of doing this? Let me know!
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’:
or if you already have a project open, go to ‘File > New Project’:
Give your project a name. I gave mine the name ‘FirstKotlin’:
Choose the defaults on the next screen. Mine looked like this:
On the ‘Add an Activity to Mobile’ dialog, choose ‘Basic Activity’:
On the ‘Customize the Activity’ screen, just leave the defaults:
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.
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.
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:
Your converted class should look something like this:
Run the application
Now, run your first Kotlin 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.
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.
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.
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.
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.
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.
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
Type inference for variable and property types
Declaration-site variance and Type projections
Separate interfaces for read-only and mutable collections