Android development with Kotlin
Kotlin was officially announced as a supported language for Android development at Google I/O 2017. I had heard of Kotlin before that, but I had never dabbled with it. This seemed like a great opportunity. Since Kotlin is fully interoperable with Java and it runs on the JVM, fans of this language used it for Android development evan before the I/O 2017, but Kotlin is now one of the officially supported Android development languages (if you don’t already know, Google officially supports C, C++ (NDK) , Java and Kotlin (SDK)).
Kotlin’s Null safety
One of the main features that make Kotlin “better than Java“, (according to the developers of the language), is the null safety. In Java, you can set a variable without initializing it. Like this:
Now is we print the length of the string s, we’ll get 15. But id we do something like this:
If we try to run this, we’ll get a message from the console that looks something like this:
Exception in thread "main" java.lang.NullPointerException
Now let’s try to do something similar in Kotlin.
Like Java, Kotlin does not allow this. Java throws a NullPointerException, but Kotlin won’t even compile.
The official Kotlin website provides a great comparison between Java nullables and Kotlin nullables. This is it:
And the same example in Kotlin:
Kotlin safe calls
Kotlin has a safe operator, and it is
?. This operator enables you to call methods which may result in returning a null.
This statement will return the length if b, if it isn’t null, or it will return null.
The !! operator
!! operator is used if you want to shoot yourself in the foot (Google I/O 2017. reference). This operator enables the NullPointerException. If the statement does not result in null, than it will return the non-null version of the result (for example a boolean), but if it does result in null, it will throw a NullPointerException