1

I tried to research it but didn't find an answer. I'm creating a data class and in that class I would like to create an array with a fixed size. I tried the following 3 options:

data class User (
    val profilePics = arrayOf("a", "b", "c")
)

data class User (
    val profilePics: Array<String>(3)
)

data class User (
    val profilePics = arrayOfNulls<String>(3)
)

But none of them work. This does work however:

data class User (
    val profilePics: Array<String>
)

How can I initialize a fixed-size strings array inside a data class

3
  • Does this answer your question? What's the Kotlin equivalent of Java's String[]? Commented Dec 24, 2019 at 9:41
  • When you are trying to make fixed size array, there is possibility you don't need array at all - just make 3 separate fields. Commented Dec 24, 2019 at 10:50
  • Also note that arrays in a data class' primary constructor properties are compared by reference during the equality checks, not by content. For that reason, you may want to use a collection or a custom data structure instead of an array. Commented Dec 24, 2019 at 17:12

3 Answers 3

1

You need type annotations on your value parameters.

The following two will compile just fine:

data class User (
    val profilePics: Array<String> = arrayOf("a", "b", "c")
)

data class User (
    val profilePics: Array<String?> = arrayOfNulls<String>(3)
)

Of course, nothing prevents the caller from passing in differently sized arrays when creating instances of any of these data classes:

val user = User(arrayOf("a", "b", "c", "d")) // compiles fine
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Robby it's working and it's interesting to know that you can pass different sizes
1

Use this :

var list:ArrayList <String> = ArrayList(5)

1 Comment

Thanks Khalid it's working now I upvoted your answer
1

try this - hope this help var array = Array(2){i ->1}

or

var array = arrayOf(1,2,3) // you can increase the size too

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.