In this article, we will give a brief intro to Kotlin programming language for Android app development. Kotlin is a modern language. Later we’ll explain with some brief code samples about Kotlin vs Java.
Introduction to Kotlin
Kotlin is an open-source, statically-typed programming language that runs on Java virtual machine. It was developed by JetBrains and open-source contributors. Kotlin first appeared in 2011 and a stable version (Kotlin 1.2) was release on 28, November 2017. Kotlin was created with Java and Android developers in mind. Its two main and most interesting features for Android developers are:Learning Curve
The learning curve of Kotlin is fairly moderate. The syntax is simple and similar to most modern programming languages. The documentation is thorough and there is a lot of help and support available in the community. Most part of the language is what we already know and differences in some concepts can be learnt in no time. The syntax is not at all like Java which is popular with Android development. However, it can be compared with Swift for iOS.Integration in Android Studio
Standard IDE for Android development means that app developers can understand, compile and run Kotlin code without any troubles or workarounds because the support for this language comes from the company that developed the IDE. There is also a code converter plugin in Android Studio that converts Java code to Kotlin.Along with having full support above Android Studio 3.0, Kotlin lets its user choose whether to target Java 6 or Java 8 compatible bytecode. It is highly interoperable with Java, which means you can continue using libraries and code written in Java while working in Kotlin. Mixed projects are also possible, with both Java and Kotlin files coexisting in the same project.Even the latest version of Android Studio i.e. 3.0.1, doesn’t support the latest version of Java i.e. Java9. It only supports Java7 and a subset of Java8 feature which also vary by platform version. With Kotlin you can use all of its functionality using Android Studio 3 and above or IDEA both development by JetBrains. It also provide following advantages over Java. There are plenty more reasons for Kotlin but we are only listing the reasons that we actively used and can discuss with development community.Kotlin vs Java: Comparison
1. Null Safety
One of the biggest advantage of Kotlin is that it’s null safe. NullPointerException (a.k.a. The Billion Dollar Mistake) is a run time exception in Java, which was removed in Kotlin and it will save you a lot of debugging time. To access a Nullable object you have to use the null safety operator i.e. “?.”. If there’s a “?” after type of an object, it is considered to be Nullable.fun doSomething(text:String?){
text?.length
}
2. Kotlin is more expressive
Kotlin is concise and expressive which means you can write more functionality with much less code. It has zero boilerplate delegation.Java example
Setting a click listener on a button in Java looks a lot confusing for a beginner and is difficult to remember without the help of suggestions from Android Studio.mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
Kotlin example
Setting a click listener on a button in Kotlin is a lot more expressive.mButton.setOnClickListener(View.OnClickListener{//code here})
3. Kotlin is Functional
Kotlin is basically an object-oriented language but as most of the modern programming languages, it uses some concepts of functional programming, such as lambda expressions and high order (functions that accept other functions as parameters).mButton.setOnClickListener({//code here})
4. Extension Functions
It provides the ability to extend the functionality of a class without inheriting it and even if you don’t have access to its source code. Whenever you want to access this, simply create an object of said class and call the function with “.” Operator.Creating an extension
fun ActionBar.setTitle(context: AppCompatActivity, title: String) {
val view: View? = context.supportActionBar?.customView
val titleTv = view?.findViewById(R.id.title)
titleTv?.text = title
}
Calling extension function
val actionBar:ActionBar = getSupportActionBar()
actionBar.setTitle(this, “Title”)
5. Smart Casts
This feature eliminates the use of explicit type casting which means if a local object passes a type check you can access it.if (x is String){
x.length
}
6. Type Inference
Most of the times you don’t have to specify the type when you declare a variable of value, as Kotlin will do it for you. But, in case it can’t infer, you have to define the variable with the full syntax.Java example
- String s = “abc”;
- char c = ‘a’;
- int i = 123;
- float f = 34f;
Kotlin example
- var s = “abc”
- var c = ‘a’
- var i = 123
- var f = 34f
7. Avoid findViewById
One of the most common and boring operation in Android development is findViewById. Although there are several alternatives like ButterKnife to improve this experience, you can simply avoid it in Kotlin using Kotlin Android Extension.//in XML Define a View Widget
//and then in Java, no need to find id of the button or to create an object loginBtn.setText(“Something Else”)
//note that id of the button is used here
8. No Static
Kotlin dropped a well-known Java constructor: the static keyword. To have its class level functionality, companion object are introduced. The main advantage of this is that everything is an object. In Java, static members are treated very differently than object members. This means that you can’t do things like implementing an interface or putting your class ‘instance’ into a map or pass it as a parameter to a method that takes Object. Companion objects allow for these things.9. Data Classes
Another great feature in Kotlin is the way it creates data classes. In Android most of the application are data driven which means we spend much time creating classes with only properties and fields to hold data. In Java this process is very tedious whereas in Kotlin this can be done in a single line.Java example
public class UserModel {
private int userId;
private String firstName;
private String lastName;
private String address;
public UserModel() {
}
public UserModel(int userId, String firstName, String lastName, String address) {
this.userId = userId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Kotlin example
data class UserModel(var userId:Int, var firstName: String, var lastName: String, var address: String)
10. No Semicolons in Kotlin
If you haven’t noticed till yet in the above code examples, there are no semicolons in Kotlin.11. String Interpolation
Or you can call it smarter and more readable version of String.format() of Java.val a = 7
val b = 3
log.d(TAG, “Sum of $a and $b = ${a+b}”) //Sum of 7 and 3 = 10
12. Default Arguments
Tired of overloading a function numerous times just because of varying arguments? Well Kotlin is bundled with default arguments.fun create (firstName:String = “user”, lastName:String = “name”, age:Int = 18){
regitster(firstName, lastName, age)
}
13. Named Arguments
With this feature you can pass the arguments in any order, or use with default arguments and there’s no need of builders.create(“John”, “Doe”, 23) //equivalent
create(firstName = “John”, lastName = “Doe”, age=23) //equivalent
create(age=23, firstName=”John”, lastName=”Doe”) //equivalent
14. When Expression
More readable and flexible version of Java’s switch case.when (x){
1 -> log.d(TAG, “x is one”)
2,3 -> log.d(TAG, “x is two or three)
in 4..10 -> log.d(TAG, “x is in range of four to ten)
else -> log.d(TAG, “x is out of range”)
}