Previous example: https://gist.github.com/tanmatra/04b049a77918b8b321ba4c37f4c582c1
Last active
July 7, 2019 20:18
-
-
Save tanmatra/17de3dd9c9350e46e99236652045a594 to your computer and use it in GitHub Desktop.
Kotlin hash code builder with inline class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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