How do I use in contract with interface?

Steven Schveighoffer schveiguy at yahoo.com
Wed Nov 15 15:14:32 UTC 2017


On 11/15/17 9:43 AM, Dr. Assembly wrote:
> I'm learning to use interface with contracts. In below code, in isn't 
> being "called". Can someone point out why? what am I doing wrong?
> 
> void main() {
>      C c = new C();
>      writeln(c.foo(1));
> }
> 
> interface I
> {
>      int foo(int i)
>          in { assert(i > 2); }
>          out (result) { assert(result != 0); }
> 
>      void baa();
> }
> 
> class C : I
> {
>      int foo(int i) {
>          return i * 2;
>      }
> 
>      void baa() {
>          writeln("Hello!");
>      }
> }

Not going to defend these design decisions, but according to 
https://dlang.org/spec/contracts.html#in_out_inheritance:

1. If a function in a derived class overrides a function in its super 
class, then only one of the in contracts of the function and its base 
functions must be satisfied. Overriding functions then becomes a process 
of loosening the in contracts.

2. A function without an in contract means that any values of the 
function parameters are allowed. This implies that if any function in an 
inheritance hierarchy has no in contract, then in contracts on functions 
overriding it have no useful effect.

So simply overriding a function and specifying no in contract cancels 
all in contracts.

I don't think there's a way to specify inheriting the in contract. I 
believe the only correct way to do this is to repeat the base's in contract.

-Steve


More information about the Digitalmars-d-learn mailing list