Category Archives: Kotlin

Kotlin Higher-Order Functions

A higher order function is a function that takes a function as a parameter or it returns a function. It allows us to write shorter and more beautiful code. Let‘s look at some examples.

fun <T> tryAndCatch(block: () -> T) = try {
    block()
} catch (e: Exception) {
    println(e.message)
}

This function will run code passed inside block variable inside try catch block and return result and also print exception in case it is thrown. What does it all mean?
Continue reading

Kotlin Constructors

Kotlin helps you make your code shorter and more readable in many areas. One of them is constructors. In Java you have to tediously assign all variables passed to the constructor in similar style

this.something = something 

If more constructors are required, you have to overload them and repeat yourself over and over. Like in the following example.
Continue reading

Static Methods and variables in Kotlin

I presume most Java programmers write some helper static methods and most probably even have some helper class including just these. So sooner or later you will need to write static methods like this in Kotlin.

public static float getPxFromDp(Context context, float dp) {
        Resources r = context.getResources();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    }

But you will find out you there is not anything like a static method in Kotlin. Fortunately, there are ways around this.
Continue reading

Kotlin Edu

There is a lot of ways how to learn Kotlin. Language reference, tutorials, video tutorials, online courses and much more. And now also Kotlin Edu.

Kotlin Educational Tools is Android Studio Plugin that helps you learn Kotlin by giving you small tasks. Read task description, write code and check. And if you cannot find the solution, you can click on Fill answer placeholders to get a right answer. Task description usually includes a link to Kotlin reference page, so you get right at the page with all you need to study to finish a task. It first looks like this.
Continue reading