Wilfred
Wilfred

Reputation: 197

Kotlin - initial an array for custom class object

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

Upvotes: 3

Views: 8825

Answers (3)

Dmitry Ivanov
Dmitry Ivanov

Reputation: 585

If you want to initialize by different known objects

        var myData = arrayOf(
           AudioItem("Tartak", "Song 1", 3.52),
           AudioItem("Topolsky", "Song 2", 5.7)
        )

Upvotes: 3

natonomo
natonomo

Reputation: 325

The simplest way with an initial size of 0 is with emptyArray:

var items = emptyArray<AudioItem>()

Upvotes: 0

zsmb13
zsmb13

Reputation: 89538

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()

Upvotes: 10

Related Questions