I am trying to add an very useful extension method to Java’s InputStream class, since we know stream parsing requires several lines of boiler plate code and In my application we need to process stream multiple times.
So far my extension function works, But it is begin really very useful for some of the drawback we are facing with kotlin core language feature.
My extension Function to Java Stream accepting single argument method definition.
fun InputStream.forEachLine(consumer: (line: String)->Unit){
val reader = BufferedReader(InputStreamReader(this, Charset.defaultCharset()))
var line: String? = null
line = reader.readLine()
while (line != null) {
consumer(line)
line = reader.readLine()
}
}
//My Test is here
@Test
fun testExtnInputStreamForEachLine() {
val stream = FileInputStream(File("c:\temp\sometextfile.txt"))
stream.forEachLine {
println(it)
if(it.equals("some text")
// I want to break the whole forEachLine block
}
}
In the above example I have the following approaches:
return@forEachLine
(this is working good for skipping the same block processing, similar to continue)- created a
run
block with label and tried with return on it. (gives compile time error) break@withLabel
(compile time error)- changed method returning
boolean
instead ofUnit
and tried returningfalse
(compile time error)