validations in value classes

前端 未结 3 1023
孤独总比滥情好
孤独总比滥情好 2021-01-06 23:09

SIP-15 implies one can use value classes to define for example new numeric classes, such as positive numbers. Is it possible to code such a constraint that the underlying >

3条回答
  •  伪装坚强ぢ
    2021-01-06 23:46

    You could use refined to lift the validation step to compile time by refining your Double with refined's Positive predicate:

    import eu.timepit.refined.auto._
    import eu.timepit.refined.numeric._
    import shapeless.tag.@@
    
    scala> implicit class Volatility(val underlying: Double @@ Positive) extends AnyVal
    defined class Volatility
    
    scala> Volatility(1.5)
    res1: Volatility = Volatility@3ff80000
    
    scala> Volatility(-1.5)
    :52: error: Predicate failed: (-1.5 > 0).
           Volatility(-1.5)
                       ^
    

    Note that the last error is a compile error and not a runtime error.

提交回复
热议问题