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

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • Does this answer your question? [What's the Kotlin equivalent of Java's String\[\]?](https://stackoverflow.com/questions/44239869/whats-the-kotlin-equivalent-of-javas-string) – Ori Marko Dec 24 '19 at 09: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. – Ircover Dec 24 '19 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. – hotkey Dec 24 '19 at 17:12

3 Answers3

1

Use this :

var list:ArrayList <String> = ArrayList(5)
Khalid Saeed
  • 131
  • 2
  • 8
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
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
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

Dipankar Baghel
  • 1,932
  • 2
  • 12
  • 24