https://kotlinlang.org logo
#announcements
Title
# announcements
p

pavi2410

08/24/2019, 7:19 PM
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

Kroppeb

08/24/2019, 7:22 PM
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

pavi2410

08/24/2019, 7:25 PM
k

Kroppeb

08/24/2019, 7:34 PM
k

karelpeeters

08/24/2019, 7:34 PM
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

pavi2410

08/24/2019, 8:39 PM
Is there any equivalent of Python's
f = (x for x in list)
generator function in Kotlin?
k

karelpeeters

08/24/2019, 10:34 PM
Python generators are just iterators:
f = list.iterator()
p

pavi2410

09/01/2019, 7:00 AM
Thanks @karelpeeters I found the solution using Iterator.
@halirutan
h

halirutan

09/01/2019, 11:52 AM
@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)
    }
}
5 Views