From 8a0c57598e83a2e9361c51ef6dce6045c1c26798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Sch=C3=BCrg?= Date: Sun, 30 Aug 2020 16:42:08 +0200 Subject: [PATCH] Enabled additon and substraction with Zero money. --- money/build.gradle | 4 ++-- .../main/java/de/tobiasschuerg/money/Money.kt | 21 ++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/money/build.gradle b/money/build.gradle index 923065a..6fd9e0d 100644 --- a/money/build.gradle +++ b/money/build.gradle @@ -9,8 +9,8 @@ android { defaultConfig { minSdkVersion 14 - versionCode 9 - versionName "0.9.0" + versionCode 10 + versionName "0.9.1" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" diff --git a/money/src/main/java/de/tobiasschuerg/money/Money.kt b/money/src/main/java/de/tobiasschuerg/money/Money.kt index eec5e23..36a0113 100644 --- a/money/src/main/java/de/tobiasschuerg/money/Money.kt +++ b/money/src/main/java/de/tobiasschuerg/money/Money.kt @@ -15,10 +15,14 @@ data class Money(val amount: BigDecimal = BigDecimal.ZERO, val currency: Currenc constructor(amount: Double, currency: Currency) : this(BigDecimal(amount), currency) constructor(amount: Long, currency: Currency) : this(BigDecimal(amount), currency) - operator fun plus(money: Money): Money { - requireSameCurrency(money) - val sum = amount.add(money.amount) - return Money(sum, currency) + operator fun plus(money: Money): Money = when { + this.isZero() -> money + money.isZero() -> this + else -> { + requireSameCurrency(money) + val sum = amount.add(money.amount) + Money(sum, currency) + } } override operator fun compareTo(other: Money): Int { @@ -59,9 +63,12 @@ data class Money(val amount: BigDecimal = BigDecimal.ZERO, val currency: Currenc } operator fun minus(money: Money): Money { - requireSameCurrency(money) - val result = amount.subtract(money.amount) - return Money(result, currency) + return if (money.isZero()) this + else { + requireSameCurrency(money) + val result = amount.subtract(money.amount) + Money(result, currency) + } } private fun requireSameCurrency(money: Money) {