问题
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:
Since the version 1.3.50 there's a guarantee in the API documentation that array elements are initialized sequentially. Therefore, you can use the original code from the question to populate an IntArray
this way.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int-array/-init-.html
回答3:
You could do return (1..n).map { nextInt() }.toIntArray()
.
来源:https://stackoverflow.com/questions/56192817/initializing-array-from-input-stream-in-kotlin