kotlincustom-data-type

Creating the analogue of BigInteger.ZERO for own data type in Kotlin


So, as is well-known, Kotlin is able to access Java libraries, and among them is the BigInteger class. And this class has a very handy feature: There is a keyword, called "BigInteger.ZERO", which returns a BigInteger object whose value equals zero.

Now I am writing a fraction data type, and I'd very much like to do the same thing for it. But the problem with just putting a val inside the class is that this first needs an object to begin with; it's not a "static" constant, so to say.

I'd be very grateful indeed for any forthcoming replies.


Solution

  • You can put the constant as a val inside the companion object of your class:

    class Fraction {
        ...
        companion object {
            val ZERO = Fraction()
        }
    }
    

    Then you can call your constant by Fraction.ZERO.

    Note that this only makes sense if your fraction class is immutable.