从Kotlin中的输入流初始化数组 [英] Initializing Array from input stream in Kotlin

查看:93
本文介绍了从Kotlin中的输入流初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从输入流中读取下一个n整数到IntArray中.

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

我写了下面的代码,但是正如我们在 Kotlin阵列初始化中的初始化调用顺序 无法保证初始化将从索引0开始并一一进行.

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

推荐答案

您总是可以自己遍历索引以保证所需的行为.

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

这篇关于从Kotlin中的输入流初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆