user11248759
user11248759

Reputation:

Kotlin weird output when using println for class instance

I'm getting Person@4b67cf4d as output.

fun main(args: Array<String>){
    var person = Person("Jimmy")
    println(person)
}


class Person(val name: String){
    var age = 10
}

Output should be Jimmy. Sorry if I'm not clear enough, I just started learning Kotlin and couldnt find solution for this.

Upvotes: 2

Views: 15266

Answers (4)

gidds
gidds

Reputation: 18627

Short answer: override toString().

Java and Kotlin have a standard way to convert any object into a String: the toString() method.

This is defined in the top-level classes java.lang.Object and in kotlin.Any, so every object is guaranteed to have this method.  The implementations there simply return the class name followed by '@' and a hex representation of the object's hashcode.  (They have to work for every possible type of object, so they don't have any other info to use.)

That's what you're seeing in your output.

If you want your class to show something more meaningful, then you should override the toString() method in your Person class.  For example, to show the name, as requested:

override fun toString() = name

However, in practice that's not always the best approach.  toString() will get called whenever your objects get printed to logs, in error messages, and similar, so it's more helpful to have a less-ambiguous representation, such as:

override fun toString() = "Person($name, $age)"

(Alternatively, you could make it a data class, which will automatically provide a suitable toString() implementation, along with several other things.)

When you want to print just then name, you can do that explicitly:

println(person.name)

Or you could provide a separate method to call, e.g.:

fun toPrettyString() = name

and then:

println(person.toPrettyString())

That would make your intent much clearer.

Upvotes: 3

Scrobot
Scrobot

Reputation: 1981

Just use data class

fun main(args: Array<String>){
    var person = Person("Jimmy")
    println(person)
}


data class Person(val name: String, var age = 10)

Output be

Person(name=Jimmy,age=10)

If you want to output exactly "Jimmy", so, output name field :)

fun main(args: Array<String>){
    var person = Person("Jimmy")
    println(person.name)
}

Upvotes: 2

forpas
forpas

Reputation: 164224

You must override the method toString() inside the Person class:

class Person(val name: String){
    var age = 10

    override fun toString(): String {
        return name
    }
}

Now your code will print:

Jimmy

and not the hashcode.

Upvotes: 9

P.Juni
P.Juni

Reputation: 2485

You should be printing a name variable of an object Person.

So its just be println(person.name)

By using println(person) you are just printing the object instance hash

Btw. you could just inline this class as class Person(val name: String, var age: Int = 10)

Upvotes: 7

Related Questions