3

Here is some code I ported over from Java:

var audioDataString = ""
        val jsonReader = BufferedReader(InputStreamReader(context.resources.openRawResource(resourceName)))
        val jsonBuilder = StringBuilder()
        var line: String? = null
        while ((line = jsonReader.readLine()) != null) {
            jsonBuilder.append(line).append("")
        }

The "(line = jsonReader.readLine())" gives me the following error: Assingments are not expressions, and only expressions are allowed in this context.

How do I do this correctly in Kotlin?

Thanks.

3 Answers 3

9

There are many different extensions in the Kotlin standard library you could make use of here for inputstreams, files, readers, etc. For this use case, Reader.forEachLine would be the simplest to use:

jsonReader.forEachLine { line ->
    jsonBuilder.append(line)
}

This lets you process an Reader line by line, and it automatically closes the Reader when the iteration is over.

You might also want to take a look at readLines, lineSequence, and useLines which could help you in more complex situations.

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

1 Comment

I didn't know this existed! I should convert my code.
4

Unfortunately, the best way I've found to do this is with a while(true):

var audioDataString = ""
        val jsonReader = BufferedReader(InputStreamReader(context.resources.openRawResource(resourceName)))
        val jsonBuilder = StringBuilder()
        var line: String? = null
        while (true) {
            line = jsonReader.readLine() ?: break
            jsonBuilder.append(line).append("")
        }

Just in case you don't know, the elvis operator (?:) checks if what's on the left is null and carries out the action on the right if it is.

Comments

0

In Kotlin, variable assignments are not considered expressions. But this is actually intended to improve the code quality. All you need is to create an iterable reader object. And you can do that using the generateSequence function:

for (line in generateSequence(::readLine)) {
    /** here you can use the line just read,
     *  and you can even add other line reading
     *  calls within this block */
}

This works for any reader that signalizes the end of sequence with null. The above example reads from stdin, but jsonReader::readLine would work as well.

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.