Library contents

Kotlin useLines

useLines gives a block a sequence of lines and closes the reader when the block ends. Consume the sequence inside that block.

A simple example

useLines

  1. Start with Two lines, A then B
  2. Do this Read one line at a time
  3. Result Two records
The line reader allows the first line to be processed before the second.

Syntax

Kotlin syntax
reader.useLines { lines -> lines.count(predicate) }
Run this example in Kotlin

Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Process a text reader while its lines are available

A program opens a reader to process records and can finish before reaching the last one. Keep operations inside the reader's lifetime and release the open resource when the work completes.

From the programval count = "north\n\nsouth".reader().buffered().useLines { lines ->
Result2
Lesson.kt
fun main() {
    val count = "north\n\nsouth".reader().buffered().useLines { lines ->
        lines.count { it.isNotBlank() }
    }
    println(count)
}
Output
2

Blank lines appear as empty strings, while an unterminated last line is still a record. Returning a lazy line sequence from the block would leave it attached to a closed reader.

Kotlin documentation for useLines

Advertisements

Read a studio sign-in sheet

A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenAda / blank / Kim
Worked result3

Read a single shift instruction

A shop closes after recording one instruction without a final newline. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenLock door + EOF
Worked result1