Reputation: 3592
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
Upvotes: 1
Views: 1114
Reputation: 2039
try this - hope this help var array = Array(2){i ->1}
or
var array = arrayOf(1,2,3) // you can increase the size too
Upvotes: 1
Reputation: 97130
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
Upvotes: 1