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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With