Just call `hashcode()`? Can you give an example?
# announcements
k
Just call
hashcode()
? Can you give an example?
l
that prints a 1 or 2 or 3 digit number depending on what's inside MyClass.
tried
hashCode()
or
javaClass.hashCode()
. the latter is always the same and is based off an interface looks like
k
Copy code
interface Foo {
    fun printHashcode() { println("Hash: ${hashCode()}") }
}

class Bar: Foo

fun main() {
    val bar = Bar()
    bar.printHashcode()
}
is this not what you want?
l
I have something like this: interface MyInterface { fun myHashCode() = "${hashCode()}" } sealed class MyClass : MyInterface { data class MyClass1(val itemId: String) : MyClass() { override fun toString() = myHashCode() } }
printing an instance of MyClass1 prints a value like "1" instead of a real hash code
k
The
hashCode
function generated by the data class probably just returns
itemId.hashCode()
and maybe that happens to be
1
for the string you're using?
l
looks like the former
so the question still stands about being able to actually print a hashcode
k
"the former"? I didn't actually say two separate things simple smile
l
1 printed is an itemId in this case
k
Can you post a full runnable example?
l
interface MyInterface { fun myHashCode() = "${hashCode()}" } sealed class MyClass : MyInterface { data class MyClass1(val itemId: Int) : MyClass() { override fun toString() = myHashCode() } } fun main(args: Array<String>) { println(MyClass.MyClass1(2)) }
prints 2
k
itemId
is an
Int
, not a
String
. The automatically generated
hashcode
implementation just returns that int as the hashcode.
l
i see. it's the hashCode implementation that Kotlin data class generates
thanks for your help @karelpeeters
k
You're welcome!