Why Kotlin

kow
12.9K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Security

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

Null safety

The following code is not possible:

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:

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?

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

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

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. Create New Content