Kotlin is a modern and adaptive programming language for Android developers. Being an Android developer, you must have a lot of experience with Java language. Java is an old programming language and very well adopted in various platforms and frameworks but Kotlin have much better features as compared to Java. Kotlin is fully inter-operable with Java code, which means one can easily use Java code along with Kotlin in the same project. Kotlin is developed by Jetbrains and is now officially supported by Android Studio. We won’t cover the syntax and how-to’s of Kotlin in this post, we’ll just try to understand the few basic and core features for now.
Kotlin Philosophy
Concise
Kotlin is a very concise programming language, it reduces a lot of boilerplate code and makes your code short by using features like inline function, lambdas expression and many more. You can easily learn Kotlin and enhance your productivity by writing short and elegant code.
Safe
Kotlin is a safe programming language, which means it is designed to avoid run-time errors. Kotlin’s type system can track if the value can be a null value at compile time and stops the compilation process by throwing NullPointerException. This makes your code free from crashes. It’s always pain for a Java developer when a program interrupts or crashes due to NullPointerException. Now we can say good-bye to run-time program crashes by using Kotlin.
Interoperable
Regarding inter-operability, your first question could be, “Can I use my existing source code or libraries with Kotlin?”. Well definitely, YES! you can easily invoke Java code inside Kotlin code or even you can convert your whole source code file into Kotlin. There is no need of any hack, you can easily use classes and methods of Java code inside Kotlin.
Performance
Kotlin is as fast and robust as Java because of its similar byte code structure. With Kotlin’s support for inline functions, lambdas run faster as compared to Java.
Compiling Kotlin Code
Kotlin code is used in file with the extension ‘.kt’ . The Kotlin compiler analyzes the source code and then generates the .class file just like Java compiler does. Compiled code of Kotlin depends upon Kotlin runtime library, which contains the definition of Kotlin’s own standard library which needs to distributed along with your application.
Kotlin is compatible with Maven, Ant and Gradle build system.
Koltin features
Kotlin covers many features which are not available in Java. Let’s discuss these features one by one.
Null Handling
Kotlin handles your null value properly. For example, in Kotlin, by default you are not allowed to assign the null value because Kotlin checks it at compile time.
1 |
var name : String = null // error : this line of code will not run |
you have to add “?” along DataType
1 |
var name : String? = null |
If you call name?.trim() this will not throw any NullPointerException even if you did not assign any value to name.
Extension
Kotlin provides extensions that enables the class to add functionality of existing classes without extending or modifying them. Kotlin supports both Extension Functions and Properties.
Extension Function
We just need to add class name prefix with the function. Following is the extension function from ViewGroup class:
1 2 3 4 |
fun ViewGroup.inflate(layoutId: Int):View { val view :View = LayoutInflater.from(context).inflate(layoutId,this,false) return view } |
We can use extension function like below:
1 2 3 4 |
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val view :View? = parent?.inflate(R.layout.item_country) return CountryViewHolder(view) } |
infix keyword
Infix keyword allows you to call member or extension function like english phrase. Function should have only one parameter and need to put infix keyboard before function.
1 2 3 |
infix fun Person.sameAs(otherPerson :Person) : Boolean { return this.personName.equals(otherPerson.personName, true) } |
Suppose we have a Person class and we added extension method to compare if two names are equal. By using infix keyword we can call the method like this:
1 2 3 |
var person = Person("Zohaib", 1) //name and id var otherPerson = Person("James", 2) //name and id var isSame = person sameAs otherPerson |
we don’t need any “.” and “()” to call function
Data Classes
We usually need classes for holding data. In Kotlin, such classes are called Data Classes that generate toString(), equals() / hasCode() and copy() functions. If you modify these functions or inherit from base class Kotlin will not generate these methods for you.
1 |
data class Country (var name : String, var flag : Flag) |
This will eliminate your extra code from class.
Sealed Classes
Sealed classes is an another new feature in Kotlin which is not available in Java. Sealed class restrict the class hierarchies, in simple words, we have a class with a specific numbers of subclasses.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
sealed class Operation { class Add : Operation() { var value : Int = 20 } class Subtract : Operation() { var value : Int = 10 } class Multiply : Operation() { var value : Int = 30 } class Division : Operation() { var value : Int = 20 } } |
The above sealed class have few sub-classes for math operations. With use of “with” we can get the real benefit of sealed class:
1 2 3 4 5 6 |
fun someMath(num : Int, operation : Operation) = when (operation) { is Operation.Add -> operation.value.plus(num) is Operation.Subtract -> operation.value.minus(num) is Operation.Multiply -> operation.value.times(num) is Operation.Division -> operation.value.div(num) } |
1 |
println(someMath(10, operation)) |
You can see the output of your desired operation in console.
Lambdas
A lambda is a way of representing a function and is a very powerful feature available in most of the modern languages like Kotlin. Lambda helps you to represent your function in a simple and elegant way.
1 2 |
val view = findViewById(R.id.view) view.setOnClickListener(view -> submitQuery() ) |
You can see the above code example of simple view click listener, left side shows the input value which in our case is, ‘view’ and on the right is the action to be performed when the button is clicked. With lambdas, you can make a function that can take function as a parameter, this is High-Order function in Kotlin.
1 |
fun setOnClickListener(listener : (view : View ) ->Unit ) {} |
Delegation
Delegation is a good option to get the advantage of inheritance without extending the super class. Kotlin supports the delegation by default with no more extra use of code.
1 2 3 4 5 6 7 8 9 10 11 |
interface Drawing { fun draw() } class Rectangle : Drawing { override fun draw() { println("Rectangle is drawing ...") } } class Square (drawing: Drawing): Drawing by drawing var rectangle = Rectangle() Square(rectangle).draw() |
The result on console will be “Rectangle is drawing …. “. You can also override the draw() function inside Square .
Object Expression & Declaration
Sometimes we need an object of some class to modify some minor things without explicitly making sub-classes. In Java, we know about anonymous classes. In Kotlin, we have object keyword for this purpose. Bellow is the example of object expression:
1 2 3 4 5 6 7 8 9 10 |
mDataModel.setRequestCompleteListener(object: RequestCompleteListener() { override fun onSuccess(response : Response) { //handle response } override fun onError(error: Error) { // handle error } }) |
In your application, you sometime need only one instance of a class that can be accessed at the global level. This instance is called Singleton . In Java, you have to implement some code logic for that, but in Kotlin you just need to add object keyword before class.
1 2 3 4 5 6 7 8 |
object DataBaseHelper { fun openConnection() { } fun closeConnection() { } } |
Kotlin makes your class singleton automatically when you put object keyword before the class name. There is no need to add class keyword here:
1 2 |
DataBaseHelper.openConnection() DataBaseHelper.closeConnection() |
Final Words
Kotlin is the new modern programming language by Google and it’s super-easy for Android developers to learn. Moreover, Java developers can swiftly migrate to Kotlin, as it requires only a click to convert your old Java code into Kotlin and being a Java developer, you can use your already developed Java libraries and code inside the Kotlin project. Android Studio now supports this language as an official platform for Android application development. Just like swift for iOS, Kotlin seems to be the future of Android Development.
Reference:
https://kotlinlang.org/