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

occz4 replies#
Cool stuff!

The use of infix functions reads a bit weird to me.
If I were to design an API like this in Kotlin, I think I would have gone for regular extensions for many cases and perhaps extension properties, think as such:

    val fiveBucks = 5.usd
    val fiveBucks = 5.money("USD")
    val tenPercent = 10.percent
How come you went for "increaseBy" and "decreaseBy" instead of overloading `plus` and `minus`? Just curious, preference is a valid answer.
nwatson#
`decreaseBy` is a multiplication and subtraction combined, map naturally to commerce domain, and is more complex than plain addition / subtraction.
sigh_again#
Nothing is preventing you from using it this way ? Infix functions are just syntactic sugar, some prefer it, some don't, but there's zero downsides to it (aside from your coworkers abusing it.) 5 money "USD" is literally the exact same thing as 5.money("USD"), and Int.usd = this.money("USD")

+ and - are already overloaded (see val subtotal = price + shipping), increase/decreaseBy are for operating over percentages (and could be written as subtotal * (1 - discount), which is much less clear). As the other comment say, it has an actual, real life meaning that people understand clearly. Your price increased by 10 percent. the By convention is also already present in the Kotlin stdlib, although it's more for grouping operations, numeric operations are taking theOf suffix now (sumBy has been deprecated in favor of sumOf, increaseBy could become increaseOf without any loss of clarity)

refulgentis5 replies#
This does a better job of showing an uneasy feeling I have about Kotlin than anything I could say.

- The infix is weird and footgun-y.
- Extension methods on int/double serving as constructors smells funny.
- Using infix operators as constructors but not using infix operators for addition/subtraction smells funny.
In general, at least in a corporate environment switching off Java for Android, I found Kotlin a distracting step sideways.
Code reviews tended to involve a lot of bikeshedding over how to make it Kotlin-y, and there's a sort of "why not?" approach to language features that creates much room for the bikeshedding.
It left me feeling like we were unconciously choosing to have the same arguments C++ programmers had in 1990, all over again. Except it was even more destructive, because those arguments were centered, and conflated with "proper" coding in the fancy new language.
I'm not against new and shiny: I was the first to use Kotlin in the org., and I dove right into Swift. There's something alarming with this transition.
I'm heartened by starting to see some debate in Android dev communities about whether Kotlin/Compose were a bridge to nowhere that shouldn't have been a focus for years.

t-writescode1 reply#
I have used Kotlin professionally for a couple-few years; and, in my experience, infix operations are a choice and you don't have to use them. - in fact, I don't think any bit of code in anything I've used uses infix operations, this is my first time seeing them in Kotlin in the wild.

For example, I haven't used them even once.
That said, I, personally, have done almost no Android programming in Kotlin, so perhaps I'm missing the main environment where such things are done? For me, Kotlin has mostly been an aggressive amount of syntactic sugar to make Java a nice experience?
And most of the DSL-style code that I write uses function pointers as the last parameter, so I can do doTheThing(parameters) { anonymous function } and that's about it?
I'm sorry that the organization you work with has aggressive bikeshedding. Perhaps this is something your organization, in general, could have a conversation about?

refulgentis1 reply#
I agree, you nailed it. Operators are something that feels like using the new shiny but are repeating well-trodden mistakes that are well-understand in languages ranging in age from C++ to Swift.

Continue this thread — 1 reply

mrcrumb13 replies#
You can bikeshed in any language. Kotlin introduced a lot of optional syntactic sugar so that Java devs could choose their level of comfort with the language features. I don't really see this as a problem unless your devs are prone to this sort of bikeshedding (see: your use of "smells funny"). I've used kotlin for Android since right before it was officially supported and there has been almost no downside other than the occasional hiccup with Java/Kotlin nullability interop
refulgentis#
Hear hear, agree whole heartedly.

Minor nit: bike shedding refers to, in the original, arguing about the color of the paint on the shed.
It follows that not all discussion is bike shedding.
In this instance, the references to C++ allude to a common best practice for programmers of avoiding custom operators, which goes far beyond an aesthetic, i.e. style, i.e. color of paint on the bike shed difference. There are engineering consequences. This also applies across languages, I'm familiar with it only from trodding the same path you are, through Swift.
Bike shedding bike shedding is indeed possible, so I won't suggest an umabiguous definition. :)
The bike shedding reference in OP is to the different flavors, but equivalent, syntactic sugar that you mention. This uses the new shiny. But this creates toxic baggage, because among other things, because to a naive implementer, there is no solid engineering reason to e.g. avoid custom operators, it's just a scarred C++ graybeard enforcing their opinion :)

wiseowise#
No, not in every language like in Kotlin.

I’ve never seen this amount of bikeshedding like in Kotlin. It’s as if whole identity of Kotlin developer is based on “do it differently from Java” which is super ironic for people who use JVM language.

beeboobaa31 reply#
> so that Java devs could choose their level of comfort with the language features

and thus complicating teamwork because there is no "right" way
kotlin is great for the lone cowboy. not so much for teams.

Continue this thread — 1 reply

zoogeny1 reply#
I hear what you are saying but there is the other side. Perhaps the opinion/feeling you are having is related to getting older.

We've learned a lot about what works and what doesn't in programming languages. Goto considered harmful and all that kind of stuff. If you want to get a Lisp/Haskell fanatic really going point out how so many of the features in those languages have finally made their way into mainstream languages (lambdas, etc.).
What we don't often consider are all of the language features that didn't make it.
This process didn't stop sometime in the past. It is happening right now. That feeling of unease may not be an indication of the quality of the features you are considering. It may largely be uncertainty about what features will or will not stand the test of time.
Perhaps as we get older, we want languages that have all of the good stuff we've learned from the past and none of the experimental stuff that we aren't too sure about yet. That might be because we are starting to notice that we won't have enough time left in our remaining days to sort all the new toys into the good/bad bin.

refulgentis1 reply#
Stirring call to action for creativity, but it is unclear how a comment that boils down to "new things might be good" applies in this context.

as OP refers to, custom operators are considered harmful in languages ranging from C++ to Swift. It's a great contemporary example of goto.

Continue this thread — 1 reply

Clamchop#
> The infix is weird and footgun-y.

If it's a foot gun, then I'm not seeing how the gun is loaded?
> Extension methods on int/double serving as constructors smells funny.
It doesn't feel meaningfully different from the static factory pattern in traditional Java, where 10.percent() would be something like MoneyUtils.createPercent() or Percent.create() with several overloads. Under the hood, that is essentially what is happening. Only downside I can see is that it muddies what truly belongs to the class, but that's true of any extension function and Kotlin is intended to be used with IDEA's introspection anyway.
The Kotlin standard library has lots of extension functions that construct new objects.
It also reminds me of Ruby, which perhaps you're also not a fan of and that's OK.

ulrikrasmussen#
I think that's more an effect of the language being new to you, and the company coding culture not having developed around it yet, than a problem with the language. Kotlin has warts, sure, but we have been using it for seven years now, and while we did have some bikeshedding in the beginning, it is virtually absent from our code reviews now. The language didn't change (well, it got even more features), but we did.
gus_massa2 replies#
> overloading `plus` and `minus`

Perhaps I'm misunderstanding your idea, but what about

  val total = price + 10.percent * 2
If the price is 10, then the total is 12 or 22?
callmeal2 replies#
>val total = price + 10.percent * 2

If the price is 10, I would expect total to be 10,2.
(price + 10.percent) * 2 would be 22.
I don't see any way to get 12.

ternaryoperator2 replies#
price + (10.percent * 2) looks like 12: If 10.percent = 1, 1*2 = 2. 10 + 2 = 12.

Under the usual rules of operator precedence, that would be the expected answer (multiplication having higher precedence than addition).

Continue this thread — 2 replies

kelnos2 replies#
How do you get 10.2? I can only think of two (reasonable) ways to think about this:

    (price + 10.percent) * 2 = (10 + 1) * 2 = 11 * 2 = 22
and

    price + (10.percent * 2) = 10 + 20.percent = 10 + 2 = 12
Personally I would assume the latter, given standard operator precedence, where multiplication precedes addition.

Continue this thread — 2 replies

occz#
I suppose that depends on how you implement `times` for the `Percent`-class. One way would be to say that 10% * 2 = 20%, making this expression evaluate to 12, in accordance with Kotlin operator precedence [1].

It's possible to avoid making this decision altogether by not implementing `times` for `Percent`, making the user have to be more explicit about what they actually want to happen - for example, requiring them to add parenthesis to arrive at 22:

    val total = (price + 10.percent) * 2
Or to arrive at 11:

    val total = price + (10 * 2).percent
[1] https://kotlinlang.org/docs/reference/grammar.html#expressio...
proper_elb1 reply#
First, congrats on the library and thank you for sharing it!

1) A hint about potential prior art: F# (and/or C#?) have a first-class unit system (physical units I think), which sounds a bit similar to monetary calculations. However, physical unit are easier to model than monetary unit I think.
2) Currently, I am building something tangentially related in Rust: A backtester (test trading strategies on historical and/or simulated data) with focus on accuracy. So one thing I included already is that Assets (like etfs) are valued in a currency.
If I may be so bold: How would you approach these questions / where could I read more about that? 1) When simulating, can I always assume that the exchange will work? (For assets, that is not always the case, sometimes one has to wait a bit until there is a buyer, or there might not be a buyer at all) 2) Is there public domain data in exchange rates? 3) If I have to choose, which exchange rate should I pick? The lower one, higher? What would make the most sense in the context of trading etfs, stocks, options, crypto etc.? 4) How to approach rounding, is there a best practise? 5) I assume it is best to immediately substract taxes in every transaction, even if they are formally defined annually, right? 6) Would you model inflation? I currently plan to ignore it and present it at the very end: "Your portfolio has a final value of X.X ¥. Adjusted for inflation, that would be Y.Y ¥ today (2024-10-08)."

eriksencosta1 reply#
The currency exchange support is way simpler than this. The library only provides a method that will calculate the monetary amount given another Money object as the rate:

val amount = 1 money "USD" // USD 1.00
val rate = 5.4905 money "BRL" // BRL 5.4905
amount exchange rate // BRL 5.49
It's up to implementers to hook up in other datasets and to consume the rates. Exchange rates datasets differ from country to country and some foreign exchange companies offer short-term contracts to hold a transaction at a given rate (sort of "guaranteed rate/price"). I don't see myself supporting this use case.
Nevertheless, Java Money (Moneta) has this feature. Never used it so, I don't know how it works.

proper_elb1 reply#
Thank you for your insights!

I think it makes sense that this feature would not be planned in your library - as I understand, its goal is to support developers to write better money-related logic, which is sometimes related but different from simulating as accurately as possible.
I just noticed a potential misuse of your API: Transitve relationships: "A" = 2.0000 "B", and "B" = 3.0000 "C", then implicitely, "A" = 6.0000 "C". Can the user now define "A" = 7.0000 "C"?
That would be wrong - but not trivial to prevent, and practically speaking, it is okay I think.
Thank you for your time and for this exchange, wish you good success and fun with kotlin money! :)

alluringorange#
Exchange rates are often not perfectly aligned, even if for a short periods of time. This is where arbitrage comes into play and levels the market.

With that we can go back to the example:
"A" = 2.0000 "B"
"B" = 3.0000 "C" -> "A" = 6.0000 "C"
"A" = 7.0000 "C"
If you notice this happening in the real world, you have the opportunity to:
1. buy 7 "C" with 1 "A"
2. buy 2 "B" with 6 "C"
3. buy 1 "A" with 2 "B"
4. keep 1 "A" profit
But it's rarely that simple and it often involves 3 or more currencies

bojanz3 replies#
I like the support for custom currencies, as that is an edge case that often pops up.

On the other hand, be careful about tying the symbol to the currency, as symbols are locale specific. For example, the symbol for USD is $ in eu-US but US$ in en-CA and en-AU (Canada and Australia), and then $US in French locales.
https://cldr.unicode.org/ is the magical dataset behind most good implementations that deal with currency display. Updated twice a year, available in JSON, providing currency symbols and formatting rules for all locales, as well as country => currency mappings and other useful information.
Disclaimer: I maintain a Go solution in this problem space: https://github.com/bojanz/currency

dkarl1 reply#
I'm curious, is there a standard practice of library developers in a certain space collaborating across languages, sharing issues and corner cases and solutions? Is this a common practice with a name? Or is it up to you to look through issues and release notes on projects in the same space to glean useful information?
andylynch#
Not sure there’s a particular name beyond ‘working group’ or ‘technical committee’.

CLDR a really interesting one though, their list of users is quite something too.

samatman2 replies#
I know this is a mere quibble as a rider on a helpful post, but a disclosure is not a disclaimer.

Disclaimers separate you from the comment, examples:
> Disclaimer: I am not a lawyer and this is not legal advice
> [says things about $company] Disclaimer: I don't work for $company, I heard this from someone who does but I can't link to a primary source
Disclosures are additional information which you think it's proper to add, to be open about your interest or stake in the topic:
> Disclosure: I wrote a similar library
> [replies to thing about $company] Disclosure: I used to work for $company

bojanz#
Right, indeed!
ahoka#
Disclaimer is more often used for humblebrag, not to disclose any information.
getfroggie3 replies#
It's kind of strange that spreadsheet languages don't support money well. Using spreadsheets for escalator style automation is actually quite good and would really be amazing in a language that took typing seriously.
eriksencosta#
I couldn't agree more as someone who has been using more spreadsheets than actually coding in the last 10 years.
ebiester5 replies#
I think there's a good reason for it to be part of a library. The problem with currencies is much like dates: they're a social construct, and change more than most of the social constructs we embed in programming languages.

I don't want to update my interpreter or compiler because Turkey changed their rules of daylight savings time, or Ethereum becomes popular.

coreload1 reply#
Yes, and sometimes the context is not just social but legal or contractual, e.g. rounding currency.
ebiester1 reply#
Yes, and rounding currency is just something that is always handled, as is the number of places that you take a currency out to - for example, gas is often priced at thousandths of a dollar rather than hundreds but presented to the customer in hundredths at the end. Or Yen in most cases does not have a decimal point, except that the places where you round or don't round can be consequential in large enough quantities.

These are largely things that can be handled by a library, but if it's in the language you best not get it wrong because it's so much harder to change!

Continue this thread — 1 reply

carapace#
This. But more than being changeable they (time and money) are supra-logical or trans-rational. In other words, computers are limited to what can be modeled or calculated with the one logical operation (it has lots of names, I like "Quine dagger") but these phenomenon are not.
skybrian#
You could say the same of Unicode, though. Some cultural abstractions become increasingly rigid because they’re embedded in computer systems everywhere.
JumpCrisscross1 reply#
Oh, this reminds me of my first job out of college at a Swiss bank. Apparently every time a currency conversion was done in a particular model, there was a routine that translated back and forth between the pre-Euro currency and Euro at the conversion rate. So a USD-EUR transaction with a party in France would be run as USD-FRF --> FRF-EUR. All in COBOL. As a result, every so often, you'd get a slightly different result running a USD-EUR trade with a party in France versus e.g. Germany or the U.K.
tomcam2 replies#
So what happened when those discrepancies arose?

Continue this thread — 2 replies

hakfoo#
There's two problems with currencies:

1. So many languages don't have a native "decimal" type to build off of, so somewhere in the data's lifecycle, a "1.75" turns into "1.7499999999997".
2. The rules around exchange rates, number of decimals, coding and symbols.
The first problem should be solved as a first-class language feature. This will discourage hacks with a "fixed point" type, where you store integer "175 cents" instead of decimal "$1.75"-- inviting huge confusion if the currency ever drops or restructures its minor unit, and supports non-money use cases where floating point inaccuracy is risky.
Item 2 makes more sense as a library. You can record that there's a 1000:1 ratio between pre-1998 and current roubles, that the symbol for the Baht will inevitably confuse Bitcoin enthusiasts, and that the Korean won no longer has any decimal places, in dynamic fields.

Continue this thread — 1 more reply

Load more comments