Write less in Kotlin
Learning a new language always seems like a challenge. And the first and the only rule of learning any programming language efficiently is to use it. Reading about the benefits of using Kotlin over other languages and watching Google I/O videos propagating Kotlin for android development definitely aspire many developers to go for it. However, in my personal experience, it is when you actually start using it in your projects that you realize its beauty and really fall for it!
Kotlin is often compared with Java. Since Java has been well-liked and chart-topping for a long time, most developers instinctively think in Java. This article presents some of the basic features that Kotlin offers and Java doesn’t, that show how much ease it provides to its users when it comes to writing the code.
Easily Constructed!
Look at the below code in Java to define a class having four members with default values and multiple constructors:
public class SmartPhone{
String modelName = "Samsung";
String modelNumber = "J500";
int displaySize = 5;
int price = 10000;//default constructor
public SmartPhone(){}
//constructor with one parameter
public SmartPhone(String name){
modelName = name;
}
//constructor with two parameter
public SmartPhone(String name, String number){
modelName = name;
modelNumber = number;
}
//constructor with three parameter
public SmartPhone(String name, String number, int size){
modelName = name;
modelNumber = number;
displaySize = size;
}
//constructor with all four parameter
public SmartPhone(String name, String number, int size, int price){
modelName = name;
modelNumber = number;
displaySize = size;
modelPrice = price;
}
//constructor with model name and size parameter
public SmartPhone(String name, int size){
modelName = name;
displaySize = size;
}
...

The Kotlin way :-
class SmartPhone (var modelName : String = "Samsung", var modelNumber : String ="G775F", var displaySize : Int = 5, var price : Int= 10000) {...}
Just to make a logical point, we need constructors to create class objects. Unlike Java, instead of making you search for the constructor definition in the code, Kotlin presents it right away — in the class header and if not, then your eyes can quickly catch it with the sensible keyword `constructor’.
Given the above class definition, you can create sixteen types of differently constructed objects
var firstObject = SmartPhone()
var secondObject = SmartPhone("Oppo")
var thirdObject = SmartPhone(modelNumber = "J260")
var fourthObject = SmartPhone(displaySize= 7)
var fifthObject = SmartPhone(price=12000)
var sixthObject = SmartPhone("Oppo","T234")
...
To check all sixteen, see here.
For it were in Java, you would need to define sixteen different constructors if you don’t wish to use builder design pattern!! The option to define default values for the parameters saves monotonous lines of codes making it concise and compact at the same time — quite insightful! Isn’t it? Of course, you cannot write more code in such types of constructors — primary constructors. In case you want to add more, then there is an init block where you can add more.
A Kotlin class can have constructor inside class body as well.
No unexpected Null Pointer Exceptions
This is really the best one! Kotlin makes sure you don’t end up with Null Pointer Exception unless you want it. And it does this so infallibly by first not letting you define a reference which cannot hold null — providing an entire new nullable type, then safely calling any property/method on it and finally giving you access to handle the nulls. Check out the following to make more sense of how Kotlin protects you from blundering your code with NPEs!
The nullable type (?)
Kotlin divides world of data types into nullable and non-null types. If you want the variable to hold null, define it suffixing the ‘?’, otherwise it cannot be null. The compiler gives error if you try to assign null to a non-null type.

Safe calls
Safe call (?.) operator lets the nullable var access a method or property only if it is not null at the time. Otherwise it will safely return null.
Consider this — a customer, Alicia, might buy a dress (or not) which might be branded (or not). To access the name of the brand,
alicia?.dress?.brand?.name
This is a chain of safe calls. It will return null if any of the properties is null. Pretty awesome right!?
Elvis operator
The Elvis operator (?:) lets you perform an action when the variable it is called on is null. In other words, it will proceed further only if it encounters a null value.
var x : String?
val l = x?.length ?: 0
This is quite useful when you want to throw an exception or return a value. The right-hand side expression of Elvis operator is evaluated only if the left-hand side is null.
Not null assertion operator
Finally, the not null assertion operator — !! — is to be used when you want your code to throw NPE. This can be applied to any variable, and if that variable is null, it will throw NPE as per your explicit request.
val l = x!!.length
Check out code related to null safety in Kotlin here.
A special class — Data class
Kotlin provides a special way to define a class that holds the data. This is great when you purposefully need such a class. This class has in-built getter and setter functions along with copy, toString, equals and hashcode methods.
Say, if we define a class for holding info of a country, its capital and population. The Java way of doing this is implementing quite a lot of code!
public class Records{
private String country;
private String capital;
private long population;//constructor
public Records(String country, String capital, long population){
this.country = country;
this.capital = capital;
this.population = population;
}//getters and setters
public String getCountry(){
return country;
}
public String setCountry(String country){
this.country = country;
} public String getCapital(){
return capital
}
public String setCapital(String capital){
this.capital = capital;
} public String getPopulation(){
return population;
}
public String setPopulation(String capital){
this.population = population;
} @Override
public int hashCode() {
final int prime = 17;
int result = 1;
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((capital == null) ? 0 : capital.hashCode());
result = prime * result + Long.hashCode(population;);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Records record = (Records) obj;
if (country== null) {
if (record.country != null)
return false;
} else if (!country.equals(record.country))
return false;
if (population != record.population)
return false;
if (capital == null) {
if (record.capital != null)
return false;
} else if (!capital.equals(record.capital))
return false;
return true;
}
@Override
public String toString() {
return "Country : " + country + ", Capital : " + capital + ", population=" + population;
}}
Same can be implemented with Kotlin’s data class as below:
data class Records (var country : String, var capital : String, var population : Long)
check complete code for data class usage here.
Extend the functionality without extending the class
This is a good look and feel feature. In Kotlin, we can define our own functions in any existing class by not actually modifying it but adding the functions we need for our use. Honestly, while using a built-in or 3rd party library, many times I wished the library provided the API for the functionality I needed — specially for String manipulations. With extension functions, at least we can use it as if it was already in the library, although we are the ones to define it.
Suppose we need an API to add spaces after each character in a string. There is no existing API for this in String class of Kotlin. We can use extension function as below and use this API on any String variable.
fun String.printCharsInString(){
for(element in this){
print("$element ")
}
}...val input = "AI787"
input.printCharsInString()Output:
A I 7 8 7
Behind the scene, extension functions are compiled as regular functions only. But, need to admit they do make code more organized and readable.
The Coroutines
Coroutines — I find to be one of the most impressive features of Kotlin. Its power is perceived as it is used. For running background tasks such as disk or network operations, we use Threads in Java. However, Kotlin’s coroutines provide quite a superior mechanism. They are faster, lighter and most importantly managed by user and not by OS. A coroutine is basically like job running on a thread or multiple threads. They never block a thread when suspended. The famous Thread.sleep() is a blocking call while delay () in a coroutine is called, another coroutine is resumed. All coroutines work cooperatively — suspending and resuming. They consume very less resources as they don’t maintain a stack but a small object in JVM heap.
Coroutines provide various constructs to endorse its amazing utility, flexibility and ease — be it running tasks concurrently or sequentially, handling timeouts or cancellation. Unlike threads which are always global, a coroutine runs in a context of some scope. CoroutineContext defines the job of the coroutine and its dispatcher (Dispatcher)– to decide on which thread or threads coroutine is running. The scope is defined by CoroutineScope — grouping some of the coroutines together to manage them.
Enough cannot be said about usefulness of coroutines. Use it to learn and learn it to use!
Making life easier

While experiencing the simplicity, conciseness and expressiveness of Kotlin, I sometimes feel that there is a human inside its compiler! :D
Thanks for reading!