Nathan Q
Nathan Q

Reputation: 1902

Variable data type

I have a class Calculation which contains a set of CalculationResult.

The CalculationResult has a property String result. It is a String, but the value can represent a calculated date, boolean, double, ...

So I was thinking of making it so that I can get the result in the right datatype:

public Date getAsDate();
public BigDecimal getAsBigDecimal();
...

But I'm not sure how I can best implement this.

Any pointers are appreciated!

Upvotes: 0

Views: 103

Answers (1)

Bozho
Bozho

Reputation: 597016

Usually you would know what result you expect from your calculation. So you can make a public class CalculationResult<T>. Then use, for example:

CalculationResult<BigDecimal> result = calculator.getResult(..);

Otherwise, if you really have your result as string, always, then the getAsX methods can be implemented via methods like Integer.parseInt(str), new BigDecimal(str) and new Date(Long.parseLong(str)) (or using a DateFormat). But note that keeping non-text as string is wrong.

Upvotes: 4

Related Questions