1

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()}
}
0

3 Answers 3

3

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()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

1 Comment

Note this results in a temporary List<Int> being created (which involves boxing).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.