Search code examples
androidkotlinrealm

Initialize Array<Int> from MutableList<Int>


I have the following code:

val realm = Realm.getDefaultInstance()
val items = realm.where(ItemRealm::class.java).equalTo("Id", id).findAll()
val ids = arrayOf<Int>(locations.map { it.locationId!! })
return realm.where(LocationRealm::class.java).`in`("id", ids).findAll()

Got the following error:

Type inference failed. Expected type mismatch: Required Int, Found List

I know that this is because the first parameter on Array constructor is Size, but I don't know how to init that array. I need it because the Realm.where.in needs an Array<Int> to work.

There's some other way (more faster) than initializing the following way?

val locations = realm.where(ItemStockLocationsRealm::class.java).equalTo("stockId", id).findAll()
val ids = arrayOf(locations.size) {0}
for (i in locations.indices) { ids[i] = locations[i]?.locationId!! }

Solution

  • val ids : Array<Int> = locations.map { it.locationId!! }.toTypedArray()