Can anyone please help me with this? I am trying t...
# announcements
p
Can anyone please help me with this? I am trying to emulate
readLine
function from stdlib which yields each line in the multiline text block. This is supposed to act just like
readLine
but reads from a fixed string instead of stdin. Here is how I'm trying to make it work: https://pl.kotl.in/f-ayPvSC-
k
The readLine is yielding all the lines at once, you have to keep a global variable that stores the list and then always yield the next one
p
k
k
You functions signature is
fun readLine(): Sequence<String>
, it returns a sequence of lines. Right now you're printing that sequence, not items from that sequence.
The stdlib readline operates on some kind of stream, which stores state. If that is really what you want to emulate (doubt it) you'll have to choose somewhere to store that state.
p
Is there any equivalent of Python's
f = (x for x in list)
generator function in Kotlin?
k
Python generators are just iterators:
f = list.iterator()
p
Thanks @karelpeeters I found the solution using Iterator.
@halirutan
h
@pavi2410 You can also re-assign System.in and System.out which gives you a solution that works no matter how you read the input.
I'm using something like that:
Copy code
fun testFunction(input: String, output: String, func: () -> Unit) {
    val oldIn = System.`in`
    val oldOut= System.out
    val inputStream = ByteArrayInputStream(input.toByteArray())
    val outputStream = ByteArrayOutputStream()
    System.setIn(inputStream)
    System.setOut(PrintStream(outputStream))
    func()
    System.setIn(oldIn)
    System.setOut(oldOut)
    assertEquals(output, outputStream.toString().trim())
    inputStream.close()
    outputStream.close()
}

fun testFunction(testCases: Map<String, String>, func: () -> Unit) {
    testCases.forEach { (input, output) ->
        testFunction(input, output, func)
    }
}