Access to object properties in a list (KOTLIN). Why is it so complicated?

Asked

Viewed 252 times

5

I’m trying to do something that I think is extremely simple: Given a class called Student, i instated 3 students and added on a list (mutableListOf). That done, I want to access the name of the students on the list.

It seems simple, doesn’t it? If I were to implement a programming language I would do so:

lista.get(1).name

But in Kotlin it’s not like that, and worse, I still haven’t figured out how!

Below is an example code:

class Student(
    name : String,
    age : Int,
    course : String,
)

fun main() {

    var s1 = Student("Ana", 25, "Eng")
    var s2 = Student("Joao", 30, "Geo")
    var s3 = Student("Flavio", 17, "Publicidade") 
    var s4 = Student("Bruno", 33, "Adm")     

    var test = mutableListOf(s1,s2,s3)
    test.add(s4)

    println(test.get(1))
}
  • Try adding val or var before the name of the variables in the constructor. https://kotlinlang.org/docs/reference/classes.html#constructors

1 answer

11

The way you declared the class Student, the variables name, age and course are only parameters passed to the constructor. If you want them to become class properties, you should add the keyword val or var before the variable name:

class Student(
    val name : String,
    val age : Int,
    val course : String
)

You can read more about the constructor syntax in the documentation.


A tip: thanks to Perator overloading, it is possible to access elements of a list with a notation similar to that of arrays:

println(test[1].name)
  • Perfect! Thank you very much, it worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.