在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
当前回答
在我的情况下,我需要初始化我的抽屉项目。我通过以下代码填充数据。
val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)
// Use lambda function to add data in my custom model class i.e. DrawerItem
val drawerItems = Array<DrawerItem>(iconsArr.size, init =
{ index -> DrawerItem(iconsArr[index], names[index])})
Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)
自定义模型类-
class DrawerItem(var icon: Int, var name: String) {
}
其他回答
简单的方法:
整数:
var number = arrayOf< Int> (10,20,30,40,50)
保持所有数据类型
var number = arrayOf(10, "string value", 10.5)
初始化数组:val paramValueList: array <String?> = arrayOfNulls<String>(5)
在我的情况下,我需要初始化我的抽屉项目。我通过以下代码填充数据。
val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)
// Use lambda function to add data in my custom model class i.e. DrawerItem
val drawerItems = Array<DrawerItem>(iconsArr.size, init =
{ index -> DrawerItem(iconsArr[index], names[index])})
Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)
自定义模型类-
class DrawerItem(var icon: Int, var name: String) {
}
你可以简单地使用现有的标准库方法,如下所示:
val numbers = intArrayOf(10, 20, 30, 40, 50)
使用一个特殊的构造函数可能是有意义的:
val numbers2 = IntArray(5) { (it + 1) * 10 }
你传递一个大小和一个lambda来描述如何初始化这些值。以下是文档:
/**
* Creates a new array of the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns an array element given its index.
*/
public inline constructor(size: Int, init: (Int) -> Int)
在全局声明int array
var numbers= intArrayOf()
方法用value初始化数组
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//create your int array here
numbers= intArrayOf(10,20,30,40,50)
}