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
- Start with Two lines, A then B
- Do this Read one line at a time
- Result Two records
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.
fun main() {
val count = "north\n\nsouth".reader().buffered().useLines { lines ->
lines.count { it.isNotBlank() }
}
println(count)
}
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
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.
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.