Lurker News
Manipulating monetary amounts is a common computing chore. However, no mainstream language has a first-class data type for representing money, it’s up to programmers to code abstractions for it. This isn’t an issue per se until dealing with rounding issues from operations like installment payments (e.g., buy now, pay later), foreign exchange, or even simple things like fee processing and tax collection.

Inspired by my days at N26 Brasil dealing with these challenges, I introduce Money: a Kotlin library that makes monetary calculations and allocations easy.

Comments (228) 50 threads

Show all comments

Showing thread 20 of 50

zellyn2 replies#
I'm new to Kotlin. Can someone explain how this function creates a Money object incorporating the given count of them?

This looks like it's ignoring the Number and creating a new Money object (of denomination 1?)
> public infix fun Number.money(currency: String): Money = money(currency, defaultRoundingMode, null)

lolinder1 reply#
It'd be easier to follow if you could provide a link to the GitHub line you're looking at, but most likely the `money` function being called is a second extension method of the Number class, which means that it implicitly gets the Number object as `this` and presumably uses it to build the Money.
thomascgalvin2 replies#
In Kotlin, an infix method can be called without the `.` operator, and without the parens surrounding arguments.

    100 money "USD"
is the same as

    100.money("USD")
`Number.money(currency: String): Money` is an extension method; Kotlin provides syntactic sugar which allows you to "add" methods to existing classes. The above is basically equivalent to:

    fun money(count: Number, currency: String): Money
zellyn#
Thanks!

I allowed myself to be distracted by all the weird infix stuff. I was thinking "but it's not passing itself into the money constructor" but it's actually just delegating to a different-signature version of `money` _on itself_ that will use its value then.

adamgordonbell#
Great see that kotlin didn't avoid all Scala's bad ideas.