Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - initial an array for custom class object

Tags:

arrays

kotlin

I am a beginner of Kotlin. I would like to initial an empty custom class array. Most Kotlin tutorials focus on primitive types Array, but not custom class Array.

I have tried the following, but it failed to work.

class MyAudioPlayer {

    // Error
    // Type mismatch: inferred type is Unit but AudioItem was expected.    
    var items: Array<AudioItem> = Array<AudioItem>(0) {}

    ......
}

Any suggestions? Thanks

like image 936
Wilfred Avatar asked Jun 17 '26 17:06

Wilfred


1 Answers

The Array constructor you're using takes a size and a lambda that creates an element for each index, for example you could use it like this (pretending that AudioItem takes an Int parameter):

var items: Array<AudioItem> = Array<AudioItem>(0) { index -> AudioItem(index) }

But to create an empty Array, you can just use arrayOf:

var items: Array<AudioItem> = arrayOf()

Or simply emptyArray:

var items: Array<AudioItem> = emptyArray()
like image 162
zsmb13 Avatar answered Jun 19 '26 10:06

zsmb13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!