Kotlin — a brief history and what’s so exciting about it:
For a moment, travel back in time with me to 2011. Back then, Kotlin was a garage project by a team at JetBrains and had already been under development for a year. The team’s main goal was to have something that had all the goodness of Scala but still compiled as fast as Java. They open-sourced the project in early 2012 under the Apache 2 License.
Since its inception, Kotlin has continued to evolve into a better programming language. Let’s take a look at some of Kotlin’s most exciting features:
- Kotlin is a Statically typed programming language — meaning it does type checking at compile-time as opposed to run-time. The advantage here is it helps in avoiding most of the problems that can creep in at run time — causing our apps to fail.
- Kotlin is open-sourced and can be used for multiple platforms. Kotlin can be used to develop applications for server-side, client-side web, and Android. This article will focus on Android app development using Kotlin, but feel free to dig deeper. Here’s a link to learn more about Server Side and Client Side Web using Kotlin.
- Kotlin is an easy-to-learn language —Kotlin is inspired by existing languages such as Java, C#, JavaScript, Scala, and Groovy. Familiarity with any of these will help you get started with Kotlin.
- And my favorite feature— Kotlin is 100% interoperable with your existing Java code base. That means you can start writing Kotlin code in your existing Java project, and it can understand and interact with Java constructs just as you would expect.
Kotlin is CONCISE 👊✅
Concision means writing less boilerplate/starter code. Kotlin documentation states that using Kotlin reduces your codebase by approximately 40% compared to using Java.
But what does it mean to me?
This concision allows you to focus more on the core functionalities you’re trying to implement.
So how is Kotlin concise?
Let’s understand how this works by looking at an example.
The Data Class:
Data classes are special kinds of classes designated to hold data — your ___Model.class is exactly what your POJO (Plain Old Java Object) classes used to be, just with less code.
In a single line, you automatically get all the getters, setters, toString(), etc.
Check out the following code to understand better:
package com.example.mykotlinapp
data class User(var name: String = "John Doe", var age: Int = 25)
## Ways to instantiate the User Data Class objects
`val u1 = User()`
> name = "John Doe" && age = 25
`val u2 = User("Jack")`
> name = "Jack" && age = 25
`val u3 = User(age = 11)`
> name = "John Doe" && age = 11
`val u4 = User("Jack", 11)`
> name = "Jack" && age = 11
`val u5 = User( age = 25, name = "Jonas")`
> name = "Jonas" && age = 25
`val u6 = User(name = "Jack", age = 11)`
> name = "Jack" && age = 11
## Changing value of a property
`u1.name = "Yash Soni"`
`u1.age = 24`
> The u1 User object is now updated with new values
Added functionality to basic data types
Kotlin has offered numerous utility functions to Native Types, thus saving the time you’ll spend on that UTILS class.
Examples:
- Have you ever had to write util functions in Java to check whether a String is Empty OR Blank OR Null? Well, in Java, you’d just get isEmpty(), but in Kotlin you have String utils like: isEmpty(), isBlank(), isNotEmpty(), isNotBlank(), isNullOrEmpty(), andisNullOrBlank()
- An Integer variable in Java gets just a few methods like compareTo() and some others to cast its value to other Java Native Types. In Kotlin, you get numerous methods like: bitwise AND OR NOT XOR, increment / decrement, division / multiplication / addition / subtraction / remainder, shift left / right, coerceAtleast, coerceAtMost, and coerceIn
Named Arguments with default values:
As we saw in the case of data class, named parameters and default values are not limited to just Class Constructor, but are available for all the methods.
// here setData is a function that takes name(String), age(Int) and country(String) as argument and does something with it.
// please note 'age' and 'country' params has a default initialization provided.
fun setData(name: String, age: Int = 1, country: String = "India") {
// some code here
}
## Ways in which you can call the setData function:
1. `setData("myUserName”)`
> here we are only passing name param value. age and country will be taken as default values, since not passed.
2. `setData(age = 20, name = "myUserName")`
> here we are passing age and name param values, by using *named arguments*. Here order of params will not matter. *country* will still default to India as no value passed.
### The benefit here is you don’t need to remember the method signature to call it. Though all advanced IDEs gives you prompt while calling a function, this is a good addition.
Kotlin is SAFE ⛑😇
This is one of the features that ultimately convinced me to try out Kotlin. Kotlin provides several means of preventing you from writing erroneous code. Such as:
The “Billion Dollar” mistake — NullPointerException
NPEs have always been unfriendly to us developers, but thanks to JetBrains, Kotlin has figured out on how can we avoid them (in most scenarios).
Variables in Kotlin can be of 2 types: Nullable & Non-Null
Nullable type variables are the ones that can hold a null value, while Non-Null type variables cannot accept a null value.
val name: String? = null
// Nullable type ----- '?' at the end of Datatype indicates that this variable can hold null values.
System.out.println(name.length)
// Compilation error on accessing length property of name variable which may be null
var output: String
// Non-Null type ----- notice the absence of '?' at the end of String type.
output = null
// Compilation error because we are trying to assign null to a Non-Null type
For example, if my data class instances are mapped to a server response, it’ll be a good decision to keep it Nullable, because a server might send in a null value for various reasons.
Safe check and Elvis Operator
You’ll be able to relate this to our very old friend Ternary Operator in Java: <EXPRESSION> ? <TRUTHY_VALUE> : <FALSY_VALUE>
val name: String? = null
// name is a nullable typed String variable
System.out.println(name?.length)
// This operation will check nullity of the variable 'name', if NOT NULL then return the length of variable 'name' else return NULL (NO NPE)
// This "?." is the Safety Check
System.out.println(name?.length ?: -1)
// This operation will check nullity of the variable 'name', if NOT NULL then return the length of variable 'name' else return -1.
// This "?:" is the Elvis Operator
!! Operator:
There is one more way to access properties of a Nullable type—by using the !! operator. This is akin to asserting that “I’m sure the variable I’m trying to access is not null, just give me what I want!” ~ DANGEROUS 🙀
If this assertion is not true, it will return an NPE. Hence, it’s not advisable to use this unless you’re 100% sure of the non-nullity of the variable.
val name: String? = null
// name is a nullable typed String variable
System.out.println(name!!.length)
// this will assert non-nullity of the variable 'name' and try to access length property of it, if 'name' is null then this will result in NPE.
Final Notes
- For all the Android — Java developers, I highly recommend trying Kotlin. The transition from Java to Kotlin is really smooth, and you’ll get familiar with Kotlin in no time.
- Using Kotlin has vastly reduced my efforts spent on trivial tasks, and NullPointerException has almost vanished from my development work.
- It also has some advanced features like Kotlin Coroutines and Kotlin Extensions that we’ll cover in the future.
- It has a wide and active community on Slack and on StackOverflow. You won’t be stuck on a problem for too long.
Be on the lookout for my next post on using Kotlin Coroutines and Kotlin Extensions!
Discuss this post on Hacker News and Reddit.
Comments 0 Responses