Skip to content

Instantly share code, notes, and snippets.

@slaykovsky
Created March 20, 2018 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slaykovsky/85b86adedaf784eeff3572d612ac339b to your computer and use it in GitHub Desktop.
Save slaykovsky/85b86adedaf784eeff3572d612ac339b to your computer and use it in GitHub Desktop.
inline fun <T> Iterable<T>.sumByPrice(selector: (T) -> Price): Price {
return this.map(selector).reduce({acc: Price, price: Price -> acc + price })
}
inline fun <T> Iterable<T>.sumByWeight(selector: (T) -> Weight): Weight {
return this.map(selector).reduce({acc: Weight, weight: Weight -> acc + weight })
}
data class Price(private val value: BigDecimal) {
operator fun plus(price: Price) = Price(this.value + price.value)
operator fun times(num: Int) = Price(this.value * BigDecimal(num))
}
data class Weight(private val value: BigDecimal) {
operator fun plus(weight: Weight) = Weight(this.value + weight.value)
operator fun times(num: Int) = Weight(this.value * BigDecimal(num))
}
data class Product(val name: String, val price: Price, val weight: Weight)
data class OrderLine(private val product: Product, private val count: Int) {
fun weight() = product.weight * count
fun amount() = product.price * count
}
object Store {
@JvmStatic
fun main(args: Array<String>) {
val toothPaste = Product(
"Tooth paste",
Price(BigDecimal(1.5)),
Weight(BigDecimal(0.5)))
val toothBrush = Product(
"Tooth brush",
Price(BigDecimal(3.5)),
Weight(BigDecimal(0.3)))
val orderLines = listOf(
OrderLine(toothPaste, 2),
OrderLine(toothBrush, 3)
)
val weight = orderLines.sumByWeight { it.weight() }
val price = orderLines.sumByPrice { it.amount() }
println("Total price: $price")
println("Total weight: $weight")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment