Kotlin – tricks and tips

Setup

buildscript {
// …
ext.kotlin_version = ‘'

dependencies {  
    classpath "org.jetbrains.kotlin" +   
        "kotlin-gradle-plugin:$kotlin_version"    
}    }   

apply plugin: ‘kotlin’

dependencies {
compile “org.jetbrains.kotlin:kotlin-stdlib-jre8”
}

Utility Functions
Favor Kotlin top-level extension functions over the typical Java utility classes. And for easier consumption within Java code, use @file:JvmName to specify the name of the Java class which would get generated by the Kotlin compiler.

// Use this annotation so you can call it from Java code
@file:JvmName(“StringUtil”)
fun String.lengthIsEven(): Boolean = length % 2 == 0
val lengthIsEven = “someString”.lengthIsEven()

Data classes
They are classes that have the specific purpose of holding data:

data class Dog(val name: String, val age: Int)

The data class will have the following function out of the box:

toString of the form “Dog(name=Mark, age=12)” equals() and hashCode() copy()

It will also become a subject for destructuring declarations:

val markTurtle = Dog(“Joe”, 50)
val (name, age) = markTurtle
println(name)

Inline functions
A lambda expression in Kotlin is translated to Java anonymous classes in Java 6 or 7, that is an overhead. Lambda calls are affecting the call stack which has a performance impact.

inline functions can be used to flat out calls instead of invoking another method call and adding that to the call stack. So it makes sense to use inline functions when we pass in the lambdas.

inline fun callBlock(block: () -> Unit) {
println(“Before calling block”)
block()
println(“After calling block”)
}

When we call callBlock it gets translated to something like the following:

callBlock { println(“The block operation”) }
String var1 = “Before calling block”;
System.out.println(var1)
String var2 = “The block operation”;
System.out.println(var2);
var1 = “After calling block”;
System.out.println(var1);

vs. the following if the function was not marked as inline

callBlock { println(“The block operation”) } callBlock((Functinos0)null.INSTANCE);

You have to be careful with inline functions though because it literary copies the method content where it is called and if the body of the functions is too large you really do not want to do this.

Knowing that, the following obviously will not make any sense because it has zero effect.

inline fun foo(noinline block: () -> Unit) {// Single lambda marked as noinline inline fun foo() { // No lambdas

Checking for null in conditions
First, you can explicitly check if b is null, and handle the two options separately:

val l = if (b != null) b.length else -1

The compiler tracks the information about the check you performed, and allows the call to length inside the if. More complex conditions are supported as well:

if (b != null && b.length > 0) print(“String of length ${b.length}”) else print(“Empty string”)

Note that this only works where b is immutable (i.e. a local variable which is not modified between the check and the usage or a member val which has a backing field and is not overridable), because otherwise it might happen that b changes to null after the check.

Safe Calls
Your second option is the safe call operator, written ?.:

b?.length

This returns b.length if b is not null, and null otherwise. The type of this expression is Int?.

Safe calls are useful in chains. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob’s department head, if any), we write the following:

bob?.department?.head?.name

Such a chain returns null if any of the properties in it is null.

Elvis Operator
When we have a nullable reference r, we can say “if r is not null, use it, otherwise use some non-null value x”:

val l: Int = if (b != null) b.length else -1

Along with the complete if-expression, this can be expressed with the Elvis operator, written ?::

val l = b?.length ?: -1

If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right. Note that the right-hand side expression is evaluated only if the left-hand side is null.

Note that, since throw and return are expressions in Kotlin, they can also be used on the right hand side of the elvis operator. This can be very handy, for example, for checking function arguments:

fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException(“name expected”)
}

The !! Operator
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()

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

Safe Casts
Regular casts may result into a ClassCastException if the object is not of the target type. Another option is to use safe casts that return null if the attempt was not successful:

val aInt: Int? = a as? Int