Scala: checking if an object is Numeric

前端 未结 2 1458
刺人心
刺人心 2021-02-02 16:36

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         


        
相关标签:
2条回答
  • 2021-02-02 17:16

    Are you using DoubleWrapper to add methods to Double? Then it should be a transparent type, i.e. you shouldn't be keeping instances, but rather define the pimped methods to return Double instead. That way you can keep using == as defined for primitives, which already does what you want (6.0 == 6 yields true).


    Ok, so if not, how about

    override def equals(o: Any): Boolean = o == value
    

    If you construct equals methods of other wrappers accordingly, you should end up comparing the primitive values again.

    Another question is whether you should have such an equals method for a stateful wrapper. I don't think mutable objects should be equal according to one of the values they hold—you will most likely run into trouble with that.

    0 讨论(0)
  • 2021-02-02 17:17

    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.

    0 讨论(0)
提交回复
热议问题