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)?
Scala Numeric Types The data type that is used is decimals (float and Double) and integers (Int, Short, Long).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With