1
votes

my problem is the following:

I created a function that returns a List. The function first creates a list with 2 Int and one String, and after that it adds an object called "Person" (which has name and age), then it return the list. In my main, I create a var that takes the value of that function, so it becomes the list. My issue is that when I try to get, for instance list[3] (that is the person), I can't called the method getName() or getAge() that I created. As you can see, Im still a noob in Kotlin. My theory is that Lists of type can't get specifical object methods, am I right? Or is there something else? Thanks in advance!

Code:

fun listTest(): List<Any>{
val list = mutableListOf(1, 3, "Hola")
val person = Person("John", 34)
list.add(person)

return list}

fun main(){
var list = listTest()
var person = list[3].getName()

I can't write getName() from list[3], Kotlin does not recognize it. Of course I created the method inside the class.

1
List<Any> means your list contains any kind of object and you don't care what type they are. When you retrieve something from your List<Any>, the compiler doesn't know what subtype of Any it is so you can't look at any of its distinct properties. You can cast the objects you retrieve, such as (list[3] as Person).getName() but this is error prone. In actual practice, there is rarely any use for a List<Any>. You usually specify a type that makes sense for what you're doing with the items that you retrieve from the list, and would rarely need a list of different types of things like this. - Tenfour04

1 Answers

5
votes

The issue is because the list is initialized as Any. Just type case is like:

if(list[3] is Person) {
    (list[3] as Person).getName()
}