Initializing Array from input stream in Kotlin

2019-08-03 14:00发布

问题:

I would like to read the next n integer from the input stream into an IntArray.

I wrote the code below but as we discussed in Order of init calls in Kotlin Array initialization there is no guarantee that the initialization would start from index 0 and go one by one.

Is there some similarly elegant solution for this which is not based on this possibly false (but as discussed in the other thread in all known implementations true) assumption?

fun Scanner.readIntArray(n: Int): IntArray {
    return IntArray(n){nextInt()}
}

回答1:

You could always iterate over the indices yourself to guarantee the behavior you want.

fun Scanner.readIntArray(n: Int) = IntArray(n).apply {
    for (i in 0 until size) {
        this[i] = nextInt()
    }
}


回答2:

You could do return (1..n).map { nextInt() }.toIntArray().