3

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

1
  • try arrayOf() instad. Commented Aug 7, 2018 at 17:55

3 Answers 3

10

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()
Sign up to request clarification or add additional context in comments.

Comments

3

If you want to initialize by different known objects

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

Comments

0

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

var items = emptyArray<AudioItem>()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.