@file:JvmName("MoneyUtils") package advanced.java import java.math.BigDecimal data class Money @JvmOverloads constructor( val amount: BigDecimal = BigDecimal.ZERO, val currency: Currency = Currency.EUR, ) { companion object { @JvmStatic fun eur(amount: String) = Money(BigDecimal(amount), Currency.EUR) @JvmStatic fun usd(amount: String) = Money(BigDecimal(amount), Currency.USD) @JvmField val ZERO_EUR = eur("0.00") } } @JvmName("sumMoney") fun List<Money>.sum(): Money? { if (isEmpty()) return null val currency = this.map { it.currency }.toSet().single() return Money( amount = sumOf { it.amount }, currency = currency ) } operator fun Money.plus(other: Money): Money { require(currency == other.currency) return Money(amount + other.amount, currency) } enum class Currency { EUR, USD }
The author:
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.