Search code examples
javainheritanceoperator-overloadingtypedefpass-by-value

Java - Creating a Pseudo Native Type


In stock trading, quantities are usually integers (e.g. 5x shares, 10x options, etc). With cryptocurrencies, quantities are fractions (e.g. 0.01 bitcoin). In both scenarios, there is typically a minimum unit (e.g. multiples of 100x shares).

I would like to wrap this logic in a Quantity class. However:

  • Java native types (e.g. double) are final, so I cannot extend them
  • Java does not support operator overloading, so arithmetic will be ugly
  • Java does not support typedefs, so I cannot wrap a double with a Quantity type

So I guess my question is this, if I want to create something akin to a native type (lots of instances, pass-by-value, lots of arithmetic), is there a "classic" Java solution? From memory, C# has a struct type which is pass-by-value, is there something similar in Java?

Thank you,

EDIT: Is it possible to import a native type from C++ code, and effectively bypass Java?


Solution

  • Yes, it is possible to declare typedefs in Java, with a guarantee of type-correctness, but without the syntactic complexity and run-time overhead of declaring a new Java class.

    As a user, you can do this by writing a type annotation and using an annotation processor at compile time. For example, you would write @Quantity int for quantities, and you would compile with javac -processor QuantityProcessor MyFile.java. You can use any arithmetic operation on a @Quantity int, and the compiler issues a warning if you mix regular ints with @Quantity ints, or if there are other errors such as a value not being in the right range or not being a multiple of 100.

    Someone needs to define the type annotations and the annotation processor, and because your requirements are unique, you will probably need to create your own. One framework that makes it easy to do create type annotations and annotation processors is the Checker Framework. (Disclosure: I am a developer.)

    The following parts of the Checker Framework manual may be particularly helpful.