0

first time posting so I apologize if anything is off!

I'm coding along a Kotlin tutorial on YouTube and I came across this problem,

I did exactly as the instructor did in the video but when he run the code, it prints the "users" in the list with the for loop.

class User (var firstName: String, var lastName: String) {

companion object {

    val users = mutableListOf<User>()

    fun createUsers(count: Int): List<User> {
        for(i in 0..count) {
            users.add(User("FirstName$i", "LastName$i"))
        }
        return users
    }
    fun createUser(firstName: String, lastName: String): User {
        return User(firstName, lastName)
    }
}

}

This is the main function:

fun main() {
val user = User.createUser("foo", "bar")
println(user)

val users = User.createUsers(5)
println(users)

}

However, when I run it on my PC, it shows me the "users" location in memory and it loops through them and I get this output:

    com.example.kotlin.User@880ec60
[com.example.kotlin.User@511baa65, com.example.kotlin.User@340f438e, com.example.kotlin.User@30c7da1e, com.example.kotlin.User@5b464ce8, com.example.kotlin.User@57829d67, com.example.kotlin.User@19dfb72a]
Process finished with exit code 0

I would really appreciate if someone can explain to me what's happening, thank you in advance!

  • That's the object's hash code, not its location in memory. See https://stackoverflow.com/questions/4712139/why-does-the-default-object-tostring-include-the-hashcode – dnault Jun 18 '21 at 19:43
  • 1
    so from what I understand, we need to either use the "data" modifier or add the function "toString()"? Thanks for the reply! –  Jun 18 '21 at 21:45

1 Answers1

0

you should use data class instead of class for the User model so to string method will be generated automatically and will print the user object

huda Olayan
  • 143
  • 1
  • 13