0

Using the latest Kotlin 1.3.10 plugin from the latest IntelliJ IDEA 2018.3, if I translate the following Java code to Kotlin:

    BufferedReader br = Files.newBufferedReader(Paths.get("filename"));
    String line;
    while ((line = br.readLine()) != null)
        System.out.println(line);

I get this:

    val br = Files.newBufferedReader(Paths.get("filename"))
    var line: String
    while ((line = br.readLine()) != null)
        println(line)

The while ((line = br.nextLine()) != null) is idiomatic Java, but its automatic translation results in illegal syntax because assignments in Kotlin are not expressions.

  1. Is this a known bug in the Java-to-Kotlin translator?

  2. What's the Kotlin idiomatic syntax equivalent to the above Java code?

4

1 Answer 1

2

I think the comments have answered both of my questions, so let me compile them into a single answer.

  1. Yes, it's a known bug, reported at youtrack.jetbrains.com/issue/KT-6294. You can vote for it (if you have a Jetbrains account) to show the developers that you would like it fixed. Thank you Alexey Belkov for bringing this to my attention.

  2. A common way to directly translate it would be:

    val br = Files.newBufferedReader(Paths.get("filename"))
    var line: String
    while (br.readLine().also { line = it} != null)
        println(line)
    

    However, a better way in this particular case is:

    val br = Files.newBufferedReader(Paths.get("filename"))
    br.forEachLine {
        println(it)
    }
    

    Or just

    File("filename").forEachLine {
        println(it)
    }
    

    (which uses a convenience method, equivalent to Java's convenience method Files.lines(Path)).

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.