Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is an extremely cool idea, but unfortunately its true potential can't be realized in Scala's type system. What you really want here is <a href="http://en.wikipedia.org/wiki/Dependent_types" rel="nofollow noreferrer">dependent types</a>, which allow you to impose a proof obligation on the caller of your method to verify that the argument is in range, such that <em>the method can't even be invoked</em> with an invalid argument. </p> <p>But without dependent types and the ability to verify specifications at compile-time, I think this has questionable value, even leaving aside performance considerations. Consider, how is it any better than using the <a href="http://daily-scala.blogspot.com/2010/03/assert-require-assume.html" rel="nofollow noreferrer"><code>require</code></a> function to state the initial conditions required by your method, like so: </p> <pre><code>def foo(i:Int) = { require (i &gt;= 0) i * 9 + 4 } </code></pre> <p>In both cases, a negative value will cause an exception to be thrown at runtime, either in the <code>require</code> function or when constructing your <code>NonNegativeDouble</code>. Both techniques state the contract of the method clearly, but I would argue that there is a large overhead in building all these specialized types whose only purpose is to encapsulate a particular expression to be asserted at runtime. For instance, what if you wanted to enforce a slightly different precondition; say, that <code>i &gt; 45</code>? Will you build an <code>IntGreaterThan45</code> type just for that method?</p> <p>The only argument I can see for building e.g. a <code>NonNegativeFoo</code> type is if you have many methods which consume and return positive numbers only. Even then, I think the payoff is dubious.</p> <p>Incidentally, this is similar to the question <a href="https://stackoverflow.com/questions/3181766/how-far-to-go-with-a-strongly-typed-language">How far to go with a strongly typed language?</a>, to which I gave a similar answer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload