Moving to kotlin for native android Java Developers

Introduction

It has been 3 years since the adoption of kotlin as an official language in the android ecosystem. Most developers had already taken the move to the new way of doing things but somehow I believe there are still a bunch of other developers (java devs ) who find it hard to make this move.

Having played around with kotlin in a production project I gathered a few lessons to help you make the transition to the new way of doing things

Disclaimer

This is not a one to one comparison between Java and kotlin but it is about tips and tricks that may help ease the transition from java to kotlin while developing android applications.

Lets get started ...

variables

final String name = "Austine";  //represents an immutable  java String

val name = "Austine"    //an immutable Kotlin String with type inference
var name = "Austine"  //a mmutable Kotlin String with type inference

and yes from the snippet above you notice that you don't need a (;) for your kotlin code

Type Inference

According to wikipedia

Type inference refers to the automatic detection of the data type of an expression in a programming language. Kotlin is a static typed language but brings along type inference so you don't have to specify the type explicitly unless it is very necessary .

This is a feature that is now available in java as of (jdk 10) which so far is not supported in android .

void vs Unit

in java void is a keyword that is used in functions to specify that the method does not return any type while it is not a type of its own. (the source of null pointer Exceptions😎)

In Kotlin there is no void but there is Unit , The type with only one value, use this incases where a java void is a candidate. while using unit there is no need for a return statement. The notion here is to have functions to at least return an object even if the object will have nothing in it (my own thinking)

Object vs Any

Java has Object to represent the root of the class hierarchy and void to represent the lack of a type. so we can say every class has Object as a superclass unless its void.

same applies to kotlin as Any type represents the super type of all non-nullable types. however there are the following key differences.

  1. As opposed to java in kotlin all primitive types inherit from Any hence you wont need implicit boxing.
  2. By default Any can't hold a null value unless you make it nullable.

new

To create instances of objects in java we use the new key word

User user = new User();  //java

we can omit the new Key word in kotlin and create class instances as you would a function call

var user = User()  //kotlin

For loops

Here I will just provide a snippet for you to see by yourself

This sample kotlin code creates a list of strings then iterates over the list printing each of them on a new line.

val names = listOf("Anne", "Peter", "Jeff")
for (name in names) {
    println(name)
}
for (x in 0..10) println(x) // Prints 0 through 10 (inclusive)

for (x in 0 until 10) println(x) // Prints 0 through 9

for (x in 0 until 10 step 2) println(x) // Prints 0, 2, 4, 6, 8

for (x in 10 downTo 0 step 2) println(x) // Prints 10, 8, 6, 4, 2, 0

switch vs when

kotlin does not have switch statements but it provides when (A switch with super powers👌)

when(number) {
    0 -> println("Invalid number")
    1, 2 -> println("Number too low")
    3 -> println("Number correct")
    4 -> println("Number too high, but acceptable")
    else -> println("Number too high")
}

As you can notice with when , There vare no complex case/break groups, only the conditions plus it can group two or more equivalent choices, separating them with a comma.

the else part is the default which is required if when returns a value otherwise it is optional.

?? operator

From Kotlin docs

One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a NullPointerException or NPE for short.

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references). For example, a regular variable of type String can not hold null:

fun main() {
    var a: String = "abc" // Regular initialization means non-null by default
    a = null // compilation error
}

//To allow nulls, we can declare a variable as nullable string, written String?

fun main() {
    var b: String? = "abc" // can be set null
    b = null // ok
    print(b)
}

//safe calls to nullable variables
val a = "Kotlin"
val b: String? = null
println(b?.length)
println(a?.length) // Unnecessary safe call

The !! Operator

if you want an NPE (nullpointerException), you can have it, but you have to ask for it explicitly, and it does not appear out of the blue.🤨

The not-null assertion operator (!!) converts any value to a non-null type and throws an exception if the value is null.

//We can write b!!, and this will return a non-null value of b 
//(e.g., a String in our example) or throw an NPE if b is null:

val l = b!!.length

Conclusion

That was a quick intro to kotlin syntax from a java developer perspective , alot of other awesome features I have omited but will leave a note for them

  1. Mixing positional and named arguments
  2. Default arguments
  3. Companion objects as static variables
  4. Lambdas
  5. it (key word
  6. Extension functions

Early this week java 15 was just released and most of the kotlin features are now in java and some even better improved so its upon you to make a choice . One thing about kotlin is that in a way it defines the future of java and the jvm.

Cheers and Happy coding...🎓🎓

MARSDEN MADOKA's photo

Great work senior

HILLARY MUTAI's photo

Great work senior

Austine Gwa's photo

Reading this and you realize something I missed or should add feel free to reach out