How to create and use an array of objects in Kotlin

2 Answers

0 votes
// Define a Class
data class Person(val name: String, val age: Int)

// Create an Array of Objects
val people = arrayOf(
    Person("Dana", 35),
    Person("Bob", 27),
    Person("Ti", 24)
)


fun main() {
    println(people[0].name) 

    // Iterating Over the Array
    for (person in people) {
    	println("${person.name} is ${person.age} years old.")
	}
}
 
  
/*
run:
  
Dana
Dana is 35 years old.
Bob is 27 years old.
Ti is 24 years old.
  
*/

 



answered May 29, 2025 by avibootz
0 votes
// Define a Class
data class Person(val name: String, val age: Int)

fun main() {
    // Create an Array of Objects
	val people = Array(3) { Person("Unknown", 0) } // Creates an array with default values
	people[0] = Person("Dana", 41)
	people[1] = Person("Bob", 61)
	people[2] = Person("Ti", 78)
    
    // Iterating Over the Array
    people.forEach { println("${it.name} is ${it.age} years old.") }
}
 
  
/*
run:
  
Dana is 41 years old.
Bob is 61 years old.
Ti is 78 years old.
  
*/

 



answered May 29, 2025 by avibootz
...