Kotlin has seen a massive boost in popularity in 2017, with an increasing number of companies using Kotlin for backend services and Google declaring Kotlin an officially supported language on Android. In this article, we showcase three examples of how we use Kotlin at Advanon to write better code.

NULL SAFETY

In Kotlin, references to objects are annotated as either nullable or not null. To declare a variable as nullable, a question mark is added to the variable type, e.g.

val a: String? = "Hello"

Any attempt to access properties of this variable without a null check will lead to a compilation error, e.g.

val l = a.length // compilation error

SAFE CALL OPERATOR

Kotlin provides a safe call operator, written as ?.. For example a?.length  returns a.length if a is not null and null otherwise. This is particularly useful when working with external APIs that return deep JSON or XML formats. To avoid a NullPointerException the following checks might need be performed in Java:

if (report != null &&
report.company != null &&
report.company.address != null) {
   return report.company.address.streetName
}

In Kotlin, we can write the same in a much more concise way:

return report?.company?.address?.streetName

DELEGATED PROPERTIES

Kotlin provides support for delegating properties. The Kotlin library provides several useful delegates out of the box and allows for custom implementations. One useful delegate provided in the Kotlin library is lazy initialization.

val a: String by lazy {
    print("Computing... ")
    "Hello"
}
println(a) // Computing... Hello
println(a) // Hello

When a is first accessed, its value gets computed and set to Hello. When the variable is accessed, the already computed value Hello is returned.

LEARN MORE

If you want to learn more about Kotlin, take a look at the official documentation and join our workshop at the WeAreDevelopers Conference in Vienna. If you are interested in working with Kotlin, please find Advanon’s current job openings here. Advanon provides a Crowd-Factoring platform that enables small and medium-sized enterprises (SMEs) in Switzerland and Germany to get their invoices directly financed by investors.

Author: Christoph Hirnschall, Advanon

Leave a Reply

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

If you agree to these terms, please click here.