From 48fd8a63eefe63e7ccc1e4050e44b18dd0911f8b Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Wed, 5 Sep 2018 21:40:36 +0300 Subject: [PATCH] Introduce Any?.hashCode() extension #KT-25039 --- libraries/stdlib/src/kotlin/util/HashCode.kt | 18 +++++++++++++ libraries/stdlib/test/utils/HashCodeTest.kt | 27 ++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 libraries/stdlib/src/kotlin/util/HashCode.kt create mode 100644 libraries/stdlib/test/utils/HashCodeTest.kt diff --git a/libraries/stdlib/src/kotlin/util/HashCode.kt b/libraries/stdlib/src/kotlin/util/HashCode.kt new file mode 100644 index 00000000000..3dfa4845028 --- /dev/null +++ b/libraries/stdlib/src/kotlin/util/HashCode.kt @@ -0,0 +1,18 @@ +/* + * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license + * that can be found in the license/LICENSE.txt file. + */ + +package kotlin + +import kotlin.internal.InlineOnly + + +/** + * Returns a hash code value for the object or zero if the object is `null`. + * + * @see Any.hashCode + */ +@SinceKotlin("1.3") +@InlineOnly +public inline fun Any?.hashCode(): Int = this?.hashCode() ?: 0 diff --git a/libraries/stdlib/test/utils/HashCodeTest.kt b/libraries/stdlib/test/utils/HashCodeTest.kt new file mode 100644 index 00000000000..729b9fb30e4 --- /dev/null +++ b/libraries/stdlib/test/utils/HashCodeTest.kt @@ -0,0 +1,27 @@ +/* + * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license + * that can be found in the license/LICENSE.txt file. + */ + +package test.utils + +import kotlin.test.Test +import kotlin.test.assertEquals + +class HashCodeTest { + @Test + fun hashCodeOfNull() { + assertEquals(0, null.hashCode()) + + val foo: Any? = null + assertEquals(0, foo.hashCode()) + } + + @Test + fun hashCodeOfNotNull() { + val value = "test" + val nullableValue: String? = value + + assertEquals(value.hashCode(), nullableValue.hashCode()) + } +} \ No newline at end of file