Kotlin Topics

Returning multiple values from a Function

This is normally a use case for Tuples which are a feature of many modern programming languages. Kotlin, however, does not have Tuples, but instead, it has another useful feature that comes in handy. It’s called Destructuring declarations.

Destructuring declarations demo
1fun <T,V> test(a: T, b: V): Pair<T, V> {
2  return Pair<T, V>(a, b)
3}
4
5val(x, y) = test(3, 4)
6print("The values are $x (${x::class.simpleName}) and $y (${y::class.simpleName})")

So, basically, you have a function that returns a Pair data class. In line 5, we assign the return value of fun test to a group of two variables. The destructuring mechanism guarantees that the first member of Pair is assigned to x and the second to y. While line 5 looks like we are declaring a tuple, we are, in fact, just declaring two ordinary variables and initialize them with the return values of the function.

Omit parentheses when calling functions

This is allowed when a function takes exactly ONE argument and that argument is a function by itself. Consider:

1fun twoAndThree(operation: (Int, Int) -> Int) {
2  val result = operation(2, 3)
3  println("The result is $result")
4}

In that case you can call the function with twoAndThree { a, b -> a + b } which is exactly the same as using twoAndThree({ a, b -> a + b }).

Try-With-Resource in Kotlin

In Java, one can write:

1try (Scanner scanner = new Scanner(new File("test.txt"))) {
2    while (scanner.hasNext()) {
3        System.out.println(scanner.nextLine());
4    }
5} catch (FileNotFoundException fnfe) {
6    fnfe.printStackTrace();
7}

There is no need for a finally() clause, because try(resource = ...) will automatically close and dispose the resource. In our case, the scanner will be closed regardless of the outcome in both the try and catch blocks.

Kotlin does not have such a construct and this is a design decision. Because Kotlin emphasizes on a functional programming model, it also uses a functional approach in the form of the use() function.

1val writer = FileWriter("test.txt")
2writer.use {
3  writer.write("something")
4}

This will automatically close writer when the scope is left. In this case this happens at line 4. The only requirement is that your object implements either Closeable() or AutoCloseable().

It is perfectly safe to use such a construct in a try {} catch {} block. Once you leave the block, your resource will be closed.

Loops and labels with break and continue