captureResults

fun <T> captureResults(f: () -> T, vararg consoleLines: String): CapturedResult<T>

Executes a function, simulating the supplied text as coming from the console (one per line) and produces the resulting function return value and console output.

Example (REPL) usage (using the input function):

>>> fun example0(): Int {
... return input().toInt() + 1
... }
>>> captureResults(::example0, "7")
res3: khoury.CapturedResult<kotlin.Int> = CapturedResult(returnedValue=8, consoleOutput=[])

Explanation:

  1. the supplied function is called, which waits for console input

  2. because "7" was supplied as an argument, this is simulated as the input to console input

  3. the function converts this to an integer and returns the result added to 1

  4. the result thus captures the function value (8) and lack of console output (as an empty list)

>>> fun example1(x: Int): String {
... println("given: $x")
... return "${x + 1}!"
... }
>>> captureResults({ example1(42) })
res2: khoury.CapturedResult<kotlin.String> = CapturedResult(returnedValue=43!, consoleOutput=[given: 42])

Notes:

  1. the supplied function requires no console input, and so none is supplied

  2. the initial println dictates the console output; the formatted string then produces the return value

>>> fun example2(): Int {
... println("get ready!")
... println("first word (new line): ")
... val w1 = input()
... print("second word (inline): ")
... val w2 = input()
... println("calculating...")
... val ans = w1.length + w2.length
... println("answer: $ans")
... return ans
... }
>>> captureResults(::example2, "howdy", "Khoury")
res3: khoury.CapturedResult<kotlin.Int> = CapturedResult(returnedValue=11, consoleOutput=[get ready!, first word (new line): , second word (inline): calculating..., answer: 11])

Notes:

  1. the supplied function makes two consecutive prompts (captured as console output; the breaks the line, the second does not) for words

  2. the resulting return value is the sum of the lengths of the two words supplied via console input

Return

results of the function, including return value and console output

Parameters

T

type of the function return

f

function to call

consoleLines

input to supply via access to console input