1

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()
}
2
  • I understand your interest is purely of academic nature. However, in case anyone comes looking for an implementation to your sample problem I suggest you mention the idiomatic solution using file.readLines().last() Commented Mar 5, 2018 at 9:42
  • FYI, I came across a discussion of the assignment from an expression. It seems this is legitimate design question for the Kotlin language which has been answered by the designers: kotlin forum Commented Mar 7, 2018 at 15:34

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.