It’s time to start using a modern programming language
I want to tell you about a new programming language called Kotlin and why you should consider it for your next project. I used to prefer Java but the last year I’ve found myself coding Kotlin whenever I could, and at this point I really can’t think of a situation where Java would be a better choice.
It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise, and makes coding a satisfying and efficient experience.
Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
So here’s a couple of reasons why you should totally switch to Kotlin (in no particular order):
Kotlin is 100% interoperable with Java. You can literally continue work on your old Java projects using Kotlin. All your favorite Java frameworks are still available, and whatever framework you’ll write in Kotlin is easily adopted by your stubborn Java loving friend.
Kotlin isn’t some weird language born in academia. Its syntax is familiar to any programmer coming from the OOP domain, and can be more or less understood from the get go. There are of course some differences from Java such as the reworked constructors or the valvar variable declarations. The snippet below presents most of the basics:
class Foo {
val b: String = "b" // val means unmodifiable
var i: Int = 0 // var means modifiable
fun hello() {
val str = "Hello"
print("$str World")
}
fun sum(x: Int, y: Int): Int {
return x + y
}
fun maxOf(a: Float, b: Float) = if (a > b) a else b
}
Kotlin will infer your types wherever you feel it will improve readability:
val a = "abc" // type inferred to String
val b = 4 // type inferred to Int
val c: Double = 0.7 // type declared explicitly
val d: List<String> = ArrayList() // type declared explicitly
The switch case is replaced with the much more readable and flexible when expression:
when (x) {
1 -> print("x is 1")
2 -> print("x is 2")
3, 4 -> print("x is 3 or 4")
in 5..10 -> print("x is 5, 6, 7, 8, 9, or 10")
else -> print("x is out of range")
}
It works both as an expression or a statement, and with or without an argument:
val res: Boolean = when {
obj == null -> false
obj is String -> true
else -> throw IllegalStateException()
}
Remember the first time you had to sort a List in Java? You couldn’t find a sort()function so you had to ask either your tutor or google to learn of Collections.sort(). And later when you had to capitalize a String, you ended up writing your own helper function because you didn’t know of StringUtils.capitalize().
If only there was a way to add new functions to old classes; that way your IDE could help you find the right function in code-completion. In Kotlin you can do exactly that:
fun String.replaceSpaces(): String {
return this.replace(' ', '_')
}
val formatted = str.replaceSpaces()
The standard library extends the functionality of Java’s original types, which was especially needed for String:
Java is what we should call an almost statically typed language. In it, a variable of type String is not guaranteed to refer to a String— it might refer to null. Even though we are used to this, it negates the safety of static type checking, and as a result Java developers have to live in constant fear of NPEs.
Kotlin resolves this by distinguishing between non-null types and nullable types. Types are non-null by default, and can be made nullable by adding a ?like so:
var a: String = "abc"
a = null // compile error
var b: String? = "xyz"
b = null // no problem
Kotlin forces you to guard against NPEs whenever you access a nullable type:
val x = b.length // compile error: b might be null
And while this might seem cumbersome, it’s really a breeze thanks to a few of its features. We still have smart casts, which casts nullable types to non-null wherever possible:
if (b == null) returnval x = b.length // no problem
We could also use a safe call ?., which evaluates to null instead of throwing a NPE:
val x = b?.length // type of x is nullable Int
Safe calls can be chained together to avoid those nested if-not-null checks we sometimes write in other languages, and if we want a default value other than null we can use the elvis operator ?::
val name = ship?.captain?.name ?: "unknown"
If none of that works for you, and you absolutely need a NPE, you will have to ask for it explicitly:
val x = b?.length ?: throw NullPointerException() // same as below
val x = b!!.length // same as above
Oh boy, is this a good lambda system — perfectly balanced between readability and terseness, thanks to some clever design choices. The syntax is first of all straight forward:
val sum = { x: Int, y: Int -> x + y } // type: (Int, Int) -> Int
val res = sum(4,7) // res == 11
And here come the clever bits:
Method parentheses can be moved or omitted if the lambda is the last or the only argument of a method.
If we choose not to declare the argument of a single-argument-lambda it’ll be implicitly declared under the name it.
These facts combined makes the following three lines equivalent:
numbers.filter({ x -> x.isPrime() })
numbers.filter { x -> x.isPrime() }
numbers.filter { it.isPrime() }
And this allows us to write concise functional code — just look at this beauty:
Kotlin’s lambda system combined with extension functions makes it ideal for DSL creation. Check out Anko for an example of a DSL that aims to enhance Android development:
You have a number of options if you intend to get started with Kotlin, but I highly recommend using IntelliJ which comes bundled with Kotlin—its features demonstrate the advantage of having the same people design both language and IDE.
Just to give you a minor but clever example, this thing popped up when I first tried to copy-paste some Java code from Stack Overflow:
IntelliJ will notice if you paste Java code into a Kotlin file
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptRead More
Privacy & Cookies Policy
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.