Skip to content

Instantly share code, notes, and snippets.

@tanmatra
Last active July 7, 2019 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanmatra/17de3dd9c9350e46e99236652045a594 to your computer and use it in GitHub Desktop.
Save tanmatra/17de3dd9c9350e46e99236652045a594 to your computer and use it in GitHub Desktop.
Kotlin hash code builder with inline class
inline class HashCode(val value: Int = INIT)
{
operator fun plus(any: Any?) = HashCode(MULTIPLIER * value + any.hashCode())
operator fun plus(int: Int) = HashCode(MULTIPLIER * value + int)
companion object {
private const val INIT = 17
private const val MULTIPLIER = 31
}
}
inline fun buildHashCode(block: (HashCode) -> HashCode): Int {
return HashCode().let(block).value
}
class Stat(
val root: String,
val data: Any,
val devices: String,
val id: Int = 55
) {
override fun hashCode(): Int = buildHashCode { it + root + data + devices + id }
override fun equals(other: Any?): Boolean = when {
other !is Stat -> false
root != other.root -> false
data != other.data -> false
devices != other.devices -> false
id != other.id -> false
else -> true
}
}
fun main() {
val stat1 = Stat("s1", "d1", "u1")
val stat2 = Stat("s1", "d1", "u1")
println("equals = ${stat1 == stat2}")
println("hashCode = ${stat1.hashCode()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment