J.E.Tkaczyk
J.E.Tkaczyk

Reputation: 587

Include both assignment and test on assigned value in while loop for Kotlin

I'm looking to find the last line of a text file using a rather standard while-loop idiom I find often used in Java.

I have a less compact version working. But the one I would like to use does not appear to be valid syntax in Kotlin. My preferred method includes an assignment and a Boolean test on that assignment in the same line.

Admittedly this is a small matter, but I'm looking to better implement my Kotlin code.

fun readLastLine(file:File):String {
    val bufferedReader = file.bufferedReader()
    var lastLine=""

    //valid
    var current = bufferedReader.readLine()
    while(current != null) {
        lastLine=current
        current = bufferedReader.readLine()
    }
    //return lastLine

    //not valid...
    //while((current=bufferedReader.readLine())!=null){
    //    lastLine=current
    //}

   //responding to comment below, 
   //preferred/terse answer using file.readLines
   //this reads all the lines into a list, then returns the last
   return file.readLines().last()
}

Upvotes: 1

Views: 714

Answers (1)

Naetmul
Naetmul

Reputation: 15592

In Kotlin, an assignment is not an expression whose value is equal to the assigned value.

You can combine two statements using run function in Kotlin. This function returns the value of the the last expression.

var current = ""
while (run {
    current = bufferedReader.readLine()
    current != null
}) { // or while (run { current = bufferedReader.readLine(); current != null }) {
    lastLine = current
}

However, you can further reduce the code using File.forEachLine() in Kotlin.

fun readLastLine(file: File): String {
    var lastLine = ""
    file.forEachLine { line ->
        lastLine = line
    }
    return lastLine
}

Or shorter,

fun readLastLine(file: File): String {
    var lastLine = ""
    file.forEachLine { lastLine = it }
    return lastLine
}

This uses BufferedReader and closes automatically internally: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/for-each-line.html

Upvotes: 5

Related Questions