Kotlin essentials

kotlin Feb 28, 2020

This is the first post in the series "Kotlin, the essence of Java". It's a reference page that will introduce some Kotlin concepts needed to understand the rest of the Kotlin series.

';' expected

First of all, no more need for the semi-colon on every single line!

Personal frustration: If the compiler is expecting it and it isn't there, why not add it!? Thank you Kotlin for removing this.

Variable types

In Kotlin, types are given after the variable name, separated by a colon:

var name: String = "Sander"

Type inference

Kotlin uses type inference if you don't specify the type explicitly. So you can write the code above like:

var name = "Sander"

val/var

In Kotlin the val and var keywords indicate fixed value or a variable. A val cannot be reassigned (like the final keyword in Java).

var myName = "Sander"
myName = "Batman" // ok

val fixedName = "Sander"
fixedName = "Joker" // compilation error

Null handling

This is where Kotlin really trumps Java! By default everything in Kotlin is non-nullable. If you want it to be nullable, you have to specify it by adding a ? to the type:

val nullable: String? = null // ok
val nonNullable: String = null // compilation error

This saves you from debugging a lot of NullPointerException cases.

Default arguments + String interpolation

Instead of function overloading, your can assign default values to method parameters:

fun sayHello(to: String = "World") {
    print("Hello, $to")
}

You can call the function with and without an argument:

sayHello() // "Hello, World"
sayHello("Sander") // "Hello, Sander"

Also, see how the parameter to is used in the printed String? No String concatenation needed.


Now that you've read the essentials, back to the series!

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.