I have defined a Class and assigned it a value, but when I try to access the value I get an @ followed by a string of hex digits. I can find out nothing in the official Kotlin documentation or online. Can anybody tell me what is happening and how to get the values I need?
This is for a Hyperskill assignment.
The program is as follows:
open class Character(val name: String)
class Jedi(name: String, val age: Int) : Character(name)
class Sith(name: String, val hasMask: Boolean) : Character(name)
fun characterBuilder(input: String): Character {
val (name, type, other) = input.split("-")
return when (type) {
"jedi" -> Jedi(name, other.toInt())
"sith" -> Sith(name, other.toBoolean())
else -> throw IllegalArgumentException("Unknown character type: $type")
}
}
fun main() {
val list = "luke-jedi-25 leia-jedi-25 darkvader-sith-true darksidiuos-sith-false".split(" ")
val characters = list.map { characterBuilder(it) }
// code won't recognize value of variable
//val (jedis, siths) = characters.partition { character -> character.type == "jedi" }
for (character in characters) { println(character) }
// println("jedis: ${jedis.size}, siths: ${siths.size}")
}
The output is:
Jedi@728938a9
Jedi@21b8d17c
Sith@6433a2
Sith@5910e440
Only a data class
automatically gets the toString
and hashCode
and equals
methods. Your classes are not data classes, so they default to the plain old Java toString
method that prints the class name and hash code.
You can define the toString
manually like this:
class Sith(val name: String, val hasMask: Boolean) : Character {
override fun toString() = "$name";
}
Or you can make your classes data classes, but data classes don't work well with inheritance. In your case, you have only the name
shared from the base class, so you could duplicate that easily:
interface Character
data class Jedi(val name: String, val age: Int) : Character
This prints:
Jedi(name=luke, age=25)
Jedi(name=leia, age=25)
darkvader
darksidiuos
Clearly, you can modify the homegrown toString
to include whatever values you want.