Kotlin:像Java中一样创建一个常规数组 [英] Kotlin: Create a regular array as in Java

查看:74
本文介绍了Kotlin:像Java中一样创建一个常规数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在Java中,我可以使用以下语法创建这样的数组:

For example, in Java I can create such an array with this syntax:

Thing box = new Thing[10];

在Kotlin中无法使用这种语法.我想在Kotlin中创建与上面相同的内容.

In Kotlin such syntax can't be used. I would like to create the equivalent of above in Kotlin.

我已经找到了Array(size: Int, init: Int -> T)方法,但是它要求我指定一个不允许使用null的初始化lambda.我想用null或我想要的大小等效的数组填充数组.

I have found the Array(size: Int, init: Int -> T) methods but it requires that I specify an init lambda that will not allow me to use null. I want to have an array filled with null or some equivalent of the size that I want.

场景:我需要有一个数据包处理程序数组,其中处理程序的索引是数据包的操作码.

The scenario: I need to have an array of packet handlers where the index of the handler is the packet's opcode.

推荐答案

使用 arrayOfNulls() .自然,您的数组将为可空类型.或者,只需使用一个列表即可.

Use arrayOfNulls(). Naturally, your array will be of nullable type. Alternatively, just use a list.

这篇关于Kotlin:像Java中一样创建一个常规数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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