Reputation: 111
I have 2 data classes, Person and Dog. Person has the following attributes:
personId, name, age, isFemale
data class Person (
val personId: Int,
val name: String,
val age: Int,
val isFemale: Boolean
)
Dog has the following attributes:
dogId, personId, name, age, isFemale
data class Dog (
val dogId: Int,
val personId: Int,
val name: String,
val age: Int,
val isFemale: Boolean
)
I want to request all the dogs of a person, by using the id attribute. But I receive an error that dogs is not initialized and empty.
fun getTestPersons(): Array<Person>{
return arrayOf(): Array<Person>(
Person(1, "Harry", 35, false)
)
}
fun getTestDogs(): Array<Dog>{
return arrayOf(
Dog(1, 1, "Bert", 4, false), Dog(2, 1, "Linda", 6, true)
)
}
currentPerson has been initialized with for example the first one.
lateinit var dogs: MutableList<Dog>
for(dog in getTestDogs()){
if(dog.personId == currentPerson.personId){
dogs.add(dog)
}
}
Expected: A MutableList with all the dogs of a specific person.
Upvotes: 0
Views: 23
Reputation: 21537
The Collection.filter function is perfect for this
getTestDogs()
.filter { dog -> dog.personId == currentPerson.personId }
.toMutableList()
Upvotes: 1