Should I use implicit conversions to enforce preconditions?

Posted by Malvolio on Stack Overflow See other posts from Stack Overflow or by Malvolio
Published on 2011-01-08T00:18:47Z Indexed on 2011/01/08 4:53 UTC
Read the original article Hit count: 249

Filed under:

It occurs to me that I could use use implicit conversions to both announce and enforce preconditions. Consider this:

object NonNegativeDouble {
  implicit def int2nnd(d : Double) : NonNegativeDouble = new NonNegativeDouble(d) 
  implicit def nnd2int(d : NonNegativeDouble) : Double = d.v
  def sqrt(n : NonNegativeDouble) : NonNegativeDouble = scala.math.sqrt(n)
}

class NonNegativeDouble(val v : Double ) {
  if (v < 0) {
    throw new IllegalArgumentException("negative value")
  }
}

object Test {
  def t1 = {
    val d : Double = NonNegativeDouble.sqrt(3.0);
    printf("%f\n", d);
    val n : Double = NonNegativeDouble.sqrt(-3.0);
  }
}

Ignore for the moment the actual vacuity of the example: my point is, the subclass NonNegativeDouble expresses the notion that a function only takes a subset of the entire range of the class's values.

First is this:

  1. A good idea,
  2. a bad idea, or
  3. an obvious idea everybody else already knows about

Second, this would be most useful with basic types, like Int and String. Those classes are final, of course, so is there a good way to not only use the restricted type in functions (that's what the second implicit is for) but also delegate to all methods on the underlying value (short of hand-implementing every delegation)?

© Stack Overflow or respective owner

Related posts about scala