Adracus
Adracus

Reputation: 1009

Compare two numbers that were previously casted as Any

Given two numbers like so

val a: Any = 1
val b: Any = 2.3

How can I generically compare these two numbers (regardless if one of these numbers is a Double, Long, Float etc.)? Most of the solutions with implicits don't work since both values have been casted to Any.

Upvotes: 0

Views: 47

Answers (1)

Gábor Bakos
Gábor Bakos

Reputation: 9100

As both can be seen as java.lang.Numbers, you can cast them to them and compare their doubleValues:

(a.asInstanceOf[Number]).doubleValue < (b.asInstanceOf[Number]).doubleValue

Scala fiddle, Scala JS fiddle.

(Be careful with Double.NaNs and large long values (thanks @PeterNeyens for reminding). In case you have to handle longs too, you should use a more complex logic.)

Upvotes: 2

Related Questions