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!

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;
}
...
Image for post
Image for post

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

The nullable type (?)

Image for post
Image for post

Safe calls

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

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

val l = x!!.length

Check out code related to null safety in Kotlin here.

A special class — Data class

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

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 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

Image for post
Image for post

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

Thanks for reading!

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store