Michael HönnigMichael Hönnig

While researching why so many people like Python, I found and article which showed how much more readable Python code is compared to Java code. I was curious how well Kotlin does that job.

The first job was to create an array of mixed data types and print these line by line. The Python and Java code can be found in Python vs Java: Which is best? Code examples and comparison for 2019 by Eric Goebelbecker. His Python code has 3 lines and 80 characters, his Java code has 8 lines and 221 characters. Here my Kotlin (actually kscript) code with 2 lines and 92 characters:

val stuff = arrayOf("Hello, World!", "Hi there, Everyone!", 6)
stuff.forEach { println(it) }

Where in this example, Python is much shorter than Java, Kotlin is not behind by much.

The second job was to create a function which reads a text file and returns a list consisting of strings each grouping 50 lines of the text file separated by commas. Eric’s Python code consists of 14 lines and 403 characters, his Java code of 18 lines with 641 characters, where the Python version is much easier to read as I have to confess.

My Kotlin code need 13 lines and only 356 characters:


import java.io.File

fun getSymbols(filename: String): MutableList<String> {
    val records = mutableListOf<String>()
    for ((index, record) in File(filename).readLines().withIndex()) {
        if (index % 5 == 0) {
            records.add(record)
        } else {
            records[records.size - 1] += ",$record" }
    }
    return records
}

Because it’s just a function it needs no main-method in Kotlin, therefore the kscript version is the same here. Additionally, to me the Kotlin version is the easiest to read.

I’ve to admit, though, that the Kotlin version keeps an extra copy of the data in memory because readLines(...) reads the whole file as List<String>.

Conclusion: For sure, as Python has many handy built-in functions and needs no type declarations, it’s sorter and more easy to read than Java. But Kotlin, especially in conjunction with kscript can compete very well.