Scala: checking if an object is Numeric

前端 未结 2 1459
刺人心
刺人心 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.

提交回复
热议问题