Last Updated:

Kotlin Good & Bad Practices for programming techniques 

Kotlin Good & Bad Practices

Good And Bad Practices Of Coding In Kotlin is an article about Kotlin programming practices, good and bad. The article discusses the good and bad techniques of programming in Kotlin.

 

The first example of programming in Kotlin

 

This is the standard way to write a line to a file: open the file and use PrintWriter write down the string. Finally, close the PrintWriter even if an exception is thrown.

You can rewrite this code like this:

fun main () {

    val file = File("/my_file")

    file.printWriter().use {

        it.println("Hello World")

    }

}

In the case of objects that implement the interface Closeable (here PrintWriter), extension function use automatically calls the close after the lambda code is executed.

Second example of Kotlin programming

 

This code loops through two lists at once. But it has one problem: if the second list is longer than the first, the application will crash with an ArrayIndexOutOfBoundsException exception

Kotlin allows you to solve this problem and at the same time make the code much more elegant:

Method zip creates a set of pairs (pairs), where the first element of the pair is a value from the first list, the second element is a value from the second with the same index. in this example the pair is automatically decomposed into variables name and number with the help of a destructive operator.

Third example of Kotlin programming

 

This code combines two lists of the same type so that their values are not duplicated. But in Kotlin, the lists have a union method that is designed to do just that:

 

Fourth example of Kotlin programming

 

This code will throw a ClassCastException because the NAME constant is not of type Int. To prevent this from happening, you can use the as? :

If type conversion is not possible, the variable x will be null.