Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: checking if an object is Numeric

Is it possible for a pattern match to detect if something is a Numeric? I want to do the following:

class DoubleWrapper(value: Double) {
  override def equals(o: Any): Boolean = o match {
    case o: Numeric => value == o.toDouble
    case _ => false
  }
  override def hashCode(): Int = value ##
}

But of course this doesn't really work because Numeric isn't the supertype of things like Int and Double, it's a typeclass. I also can't do something like def equals[N: Numeric](o: N) because o has to be Any to fit the contract for equals.

So how do I do it without listing out every known Numeric class (including, I guess, user-defined classes I may not even know about)?

like image 559
dhg Avatar asked Aug 18 '12 17:08

dhg


People also ask

Is Numeric in Scala?

Scala Numeric Types The data type that is used is decimals (float and Double) and integers (Int, Short, Long).

How do you check if a string is a digit Scala?

The isDigit() method is utilized to check if the stated character is digit or not. Return Type: It returns true if the stated character is digit else it returns false.

How do you check if an object is an int?

Use the int() Method to Check if an Object Is an int Type in Python. We can create a simple logic also to achieve this using the int function. For an object to be int , it should be equal to the value returned by the int() function when this object is passed to it.


1 Answers

The original problem is not solvable, and here is my reasoning why:

To find out whether a type is an instance of a typeclass (such as Numeric), we need implicit resolution. Implicit resolution is done at compile time, but we would need it to be done at runtime. That is currently not possible, because as far as I can tell, the Scala compiler does not leave all necessary information in the compiled class file. To see that, one can write a test class with a method that contains a local variable, that has the implicit modifier. The compilation output will not change when the modifier is removed.

like image 85
Kim Stebel Avatar answered Sep 30 '22 03:09

Kim Stebel