1

I'm using a case class which - among other parameters - is instantiated with a BigInt hexadecimal value. I use this case class to deserialize JSON messages via Jerkson/Jackson. The beauty of using Jackson is that the de/serialization works out-of-the-box for case classes based on their signature (I guess).

Now, a BigInt value in hexadecimal encoding would need to be instantiated with an additional radix parameter: BigInt(hexValue, 16). However my JSON messages don't contain such parameter. I'm looking for a solution to define this radix within my case class' definition so that Jackson would continue be able to use the class without configuration. Something like:

case class MyClass(name: String, hexValue: BigInt(hexValue, 16))

I understand that alternative approaches would be to a) define the JSON de/serialization explicitly or to b) define my own wrapper class around BigInt. However I'm looking for a more elegant and "scala-ish" solution - if there is any.

Note: Int is not sufficient, it has to be BigInt.

Randall Schulz
  • 26,420
  • 4
  • 61
  • 81
jans
  • 1,768
  • 3
  • 17
  • 22

2 Answers2

2

You can override the apply method to customize case class instantiation..

case class MyClass (name: String, hexValue: BigInt)

object MyClass{
  def apply(name: String, hexValue: String) = 
                            new MyClass(name,BigInt(hexValue,16))
}

Use it as

MyClass("Foo","29ABCDEF")   //> res0: MyClass = MyClass(Foo,699125231)
Shrey
  • 2,374
  • 3
  • 21
  • 24
1

I think your best bet is to go with the wrapper on BigInt. Something like

import  java.math.BigInteger

class   BigHexInt(hexString: String)
extends BigInt(new BigInteger(hexString, 16))

Then write your case class using BigHexInt:

case class MyClass(name: String, bigHex: BigHextInt)
Randall Schulz
  • 26,420
  • 4
  • 61
  • 81