在构造函数中初始化Array类属性

时间:2019-05-08 16:20:18

标签: android kotlin

我是Kotlin的新手,我试图了解如何以正确的方式初始化此数组。

我的Java代码:

 private Bitmap[] leftToRights;
 private Bitmap[] rightToLefts;
 private Bitmap[] topToBottoms;
 private Bitmap[] bottomToTops;


 //On constructor(colCount = 3)
 this.topToBottoms = new Bitmap[colCount]; // 3
 this.rightToLefts = new Bitmap[colCount]; // 3
 this.leftToRights = new Bitmap[colCount]; // 3
 this.bottomToTops = new Bitmap[colCount]; // 3

在Kotlin(我尝试):

//Declaration
private val leftToRights: Array<Bitmap>
private val rightToLefts: Array<Bitmap>
private val topToBottoms: Array<Bitmap>
private val bottomToTops: Array<Bitmap> 

//Init
Array<Bitmap>(colCount,/*Missing argument, what shall I initialize with?*/)
this.topToBottoms = Array<Bitmap>(colCount,/*Missing argument, what shall I initialize with?*)
this.rightToLefts = Array<Bitmap>(colCount,/*Missing argument, what shall I initialize with?*)
this.leftToRights = Array<Bitmap>(colCount,/*Missing argument, what shall I initialize with?*)
this.bottomToTops = Array<Bitmap>(colCount,/*Missing argument, what shall I initialize with?*)

那么与Java一样,初始化这些数组的好方法是什么?有人可以解释一下它在Java中的工作方式吗,java是否用null初始化Bitmap数组?

对不起,我的英语,希望您能理解。我对此帖子有任何疑问。

5 个答案:

答案 0 :(得分:1)

在kotlin中,如果要使用null初始化数组,则必须使其接受null作为值。

为此,您将执行以下操作:

private val leftToRights: Array<Bitmap?> = arrayOf(null, null, null)

通过指定它是Bitmap?而不是Bitmap的数组,由于每一项都是可选的位图,因此您可以将其设置为null的数组。

答案 1 :(得分:1)

科特林中,您可以使用lateinit声明数组:

strcat()

请注意,如果要在初始化数组时使用空值填充数组,则必须使用private lateinit var leftToRights: Array<Bitmap?> 而不是Bitmap?,并且还必须使用Bitmap而不是var因为val仅在可变属性上被允许。
稍后使用arrayOfNulls()使用所需的大小初始化数组:

lateinit

答案 2 :(得分:0)

回答第二个问题,是的,Java中具有非原始类型的对象字段将以null初始化。

除了先前的响应之外,如果您不想使用var lateinit,并且您更喜欢代码可读性而不是固定大小数组的性能提高,则可以使用以下方法:

private val leftToRights = mutableListOf<Bitmap>()
private val rightToLefts = mutableListOf<Bitmap>()
private val topToBottoms = mutableListOf<Bitmap>()
private val bottomToTops = mutableListOf<Bitmap>()

P.S。我很乐意对此发表评论,而不是回覆,但我没有足够的声誉:(

答案 3 :(得分:0)

根据您的设计,P_GridMax[i]数组中的值可以为null。在Kotlin中,这由类型为Bitmap的数组反映。考虑到这一点,下面的Array<Bitmap?>类将起作用:

Rows

通过这种方式,您不需要class Bitmap class Rows(val colCount: Int) { val leftToRights by lazy { init() } val rightToLefts by lazy { init() } val topToBottoms by lazy { init() } val bottomToTops by lazy { init() } private fun init() = Array<Bitmap?>(colCount) { null } } fun main() { val rows = Rows(3) with(rows) { leftToRights[1] = Bitmap() println(leftToRights[0]) // null println(leftToRights[1]) // Bitmap@... println(leftToRights[2]) // null } } (懒惰为您完成此操作)并且您不需要使用lateinithttps://kotlinlang.org/docs/reference/delegated-properties.htmlvar的工作方式的说明

答案 4 :(得分:0)

在Kotlin中使用null初始化数组的方法有多种:

val leftToRights: Array<Bitmap?> = arrayOf(null, null, null)
val leftToRights = Array<Bitmap?>(3){_ -> null }
val leftToRights = arrayOfNulls<Bitmap?>(3)