Initializing Array from input stream in Kotlin

不羁岁月 提交于 2019-12-11 06:34:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!