Search code examples
scalascala-2.10

How do I get an object's type and pass it along to asInstanceOf in Scala?


I have a Scala class that reads formatting information from a JOSN template file, and data from a different file. The goal is to format as a JSON object specified by the template file. I'm getting the layout working, but now I want to set the type of my output to the type in my template (i.e. if I have a field value as a String in the template, it should be a string in the output, even if it's an integer in the raw data).

Basically, I'm looking for a quick and easy way of doing something like:

output = dataValue.asInstanceOf[templateValue.getClass]

That line gives me an error that type getClass is not a member of Any. But I haven't been able to find any other member or method that gives me an variable type at runtime. Is this possible, and if so, how?

Clarification

I should add, by this point in my code, I know I'm dealing with just a key/value pair. What I'd like is the value's type.

Specifically, given the JSON template below, I want the name to be cast to a String, age to be cast to an integer, and salary to be cast a decimal on output regardless of how it appears in the raw data file (it could be all strings, age and salary could both be ints, etc.). What I was hoping for is a simple cast that didn't require me to do pattern matching to handle each data type specifically.

Example template:

people: [{  
    name: "value",  
    age: 0,  
    salary: 0.00  
}]

Solution

  • Type parameters must be known at compile time (type symbols), and templateValue.getClass is just a plain value (of type Class), so it cannot be used as type parameter. What to do instead - this depends on your goal, which isn't yet clear to me... but it may look like

    output = someMethod(dataValue, templateValue.getClass),

    and inside that method you may do different computations depending on second argument of type Class.