# Why Kotlin

kow
1,970 views

### Security

Kotlin is more secure than Java, mainly due to two language features

#### Null safety

The following code is not possible:

// {...}
var a: String = "abc"
a = null // compilation error
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Variables in Kotlin are not nullable unless explicitely stated. How do we prevent a compilation error in the above piece of code?

Solution

Add a "?" to the value type to allow this:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

But if you want to do something with those nullable values, you have to check for null: (Using the ?. operator. This is the "null safe dot operator", or "safe call operator").

==> Before running the snippet further down: what do you think is displayed?

// {...}
var a: String? = null
println(a?.length)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

See https://kotlinlang.org/docs/reference/null-safety.html for more examples. If you are familier with freemarker you might recognise similarites: https://freemarker.apache.org/docs/dgui_template_exp.html#dgui_template_exp_missing

#### Emphasis on Immutabilty

Shared mutable state is the root of all evil

Kotlin has one main constructs to prevent shared mutable state:

### val vs var keyword

// {...}
val a: String? = "abc"
println(a)
a = "bcd"
println(a)
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

This code fails, because it reassigns to a val, you would have to change above code to a var.

This also works with java, using the "final" keyword

//{...}
final int a = 1;
System.out.println(a);
a = 2;
System.out.println(a);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

But there are some issues with the final keyword, mainly that it is ambigous: it is both used to declare variables immutable and to put constraints on inheritance. Furthermore you always have to ask yourself if you really want to use a var in Kotlin, while in Java you have to not forget the final keyword

Open Source Your Knowledge: become a Contributor and help others learn.