On 04/16/2012 08:15 PM, Eyyub wrote:
On Friday, 13 April 2012 at 22:23:25 UTC, Ali Çehreli wrote:
On 04/13/2012 03:07 PM, Eyyub wrote:
Hai,
After watching Walter's video at Lang.NEXT, I have wanted to know how
contracts inheritance works.
In the following code, I don't understand why foo.bar(2) works...but
with the sames contracts in the foo function it doesn't work.
http://paste.pocoo.org/show/3Ab5IiQk6hTiJ0jAFZWv/
Thanks
Here is the for convenience:
import std.stdio;
interface IFoo
{
void bar(int a)
in
{
assert(a != 1);
}
}
class Foo : IFoo
{
this()
{}
override void bar(int a)
in
{
assert(a != 2);
}
body
{
writeln(a); // 2
}
}
void foo(int a)
in
{
assert(a == 2);
assert(a < 2);
}
body
{
writeln(a);
}
void main()
{
foo(2); // don't pass
Foo foo2 = new Foo;
foo2.bar(2); // pass
}
foo(2) cannot work because of the second assert in the 'in' contract.
foo2.bar(2) passes because passing a single 'in' contract is
sufficient. The 'in' contract of IFoo.bar() requires that a != 1 and
it is satisfied for 2 so bar() can be called with argument 2.
Ali
Mhh ok thanks.
So, why overrides a contract if the assert is not checked at runtime ?
Eyyub,
A contract of an override can only lower the restrictions.
So when the in contract for IFoo.bar passes there is no need to check
the contract of Foo.bar since it must accept anything that IFoo.bar
whould accept.
When the contract for IFoo.bar fails then the contract for Foo.bar is
checked, since it may accept more then IFoo.bar.
--
Mike Wey