diff --git a/changelog.md b/changelog.md index b544fa7b8..245783179 100644 --- a/changelog.md +++ b/changelog.md @@ -32,7 +32,7 @@ class NotEmptyList : NotEmptyCollection class NotEmptySet : NotEmptyCollection ``` -- Binary operations (`plus`, `minus`) for the `AnyInt` hierarchy (issue +- Binary operations (`plus`, `minus`, `times`) for the `AnyInt` hierarchy (issue [#31](https://github.com/kotools/types/issues/31)). ```kotlin diff --git a/src/commonMain/kotlin/kotools/types/number/AnyInt.kt b/src/commonMain/kotlin/kotools/types/number/AnyInt.kt index ac517cebc..0c7e999a3 100644 --- a/src/commonMain/kotlin/kotools/types/number/AnyInt.kt +++ b/src/commonMain/kotlin/kotools/types/number/AnyInt.kt @@ -47,6 +47,18 @@ public operator fun AnyInt.minus(other: Int): Int = toInt() - other @SinceKotoolsTypes("4.1") public operator fun AnyInt.minus(other: AnyInt): Int = toInt() - other +/** Multiplies this integer by the [other] one. */ +@SinceKotoolsTypes("4.1") +public operator fun Int.times(other: AnyInt): Int = this * other.toInt() + +/** Multiplies this integer by the [other] one. */ +@SinceKotoolsTypes("4.1") +public operator fun AnyInt.times(other: Int): Int = toInt() * other + +/** Multiplies this integer by the [other] one. */ +@SinceKotoolsTypes("4.1") +public operator fun AnyInt.times(other: AnyInt): Int = toInt() * other + internal sealed interface AnyIntSerializer : KSerializer { val serialName: Result diff --git a/src/commonTest/kotlin/kotools/types/number/AnyIntTest.kt b/src/commonTest/kotlin/kotools/types/number/AnyIntTest.kt index c3140d1b9..e6ed9ae2e 100644 --- a/src/commonTest/kotlin/kotools/types/number/AnyIntTest.kt +++ b/src/commonTest/kotlin/kotools/types/number/AnyIntTest.kt @@ -57,6 +57,30 @@ class AnyIntTest { val result: Int = x - y result shouldEqual x.toInt() - y.toInt() } + + @Test + fun int_times_should_pass_with_an_AnyInt() { + val x: Int = Random.nextInt() + val y: AnyInt = NonZeroInt.random() + val result: Int = x * y + result shouldEqual x * y.toInt() + } + + @Test + fun times_should_pass_with_an_Int() { + val x: AnyInt = PositiveInt.random() + val y: Int = Random.nextInt() + val result: Int = x * y + result shouldEqual x.toInt() * y + } + + @Test + fun times_should_pass_with_an_AnyInt() { + val x: AnyInt = PositiveInt.random() + val y: AnyInt = NegativeInt.random() + val result: Int = x * y + result shouldEqual x.toInt() * y.toInt() + } } class AnyIntSerializerTest {