# Contract to indicate boolean state in lambda function?

**URL:** <https://discuss.kotlinlang.org/t/contract-to-indicate-boolean-state-in-lambda-function/17106>\
**Category:** Language Design\
**Created:** [April 14, 2020, 2:34am UTC](https://discuss.kotlinlang.org/t/contract-to-indicate-boolean-state-in-lambda-function/17106 "2020-04-14T02:34:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Loke](https://avatars.discourse-cdn.com/v4/letter/l/c68b51/32.png) [@Loke](https://discuss.kotlinlang.org/u/Loke)\
**Post date:** [April 14, 2020, 2:34am UTC](https://discuss.kotlinlang.org/t/contract-to-indicate-boolean-state-in-lambda-function/17106/1 "2020-04-14T02:34:05Z")

</div>

I have built the following implementation of `unless`:

```auto
inline fun unless(cond: Boolean, fn: () -> Unit) {
    contract { callsInPlace(fn, InvocationKind.AT_MOST_ONCE) }
    if (!cond) {
        fn()
    }
}

```

Is there a way to specify in the contract that `fn` will only be invoked if `cond` is false? That is needed in order for smart casts to work in the following code:

```auto
unless(x is Foo) {
    throw SomeException("x is not Foo");
}
x.someMethodOnFoo() // This will not smart cast

```

Is there a way to achieve this?

---

<div class="post-metadata">

**Author:** ![SackCastellon](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/sackcastellon/32/4553_2.png) [@SackCastellon](https://discuss.kotlinlang.org/u/SackCastellon)\
**Post date:** [April 14, 2020, 10:30am UTC](https://discuss.kotlinlang.org/t/contract-to-indicate-boolean-state-in-lambda-function/17106/2 "2020-04-14T10:30:26Z")

</div>

It cannot smart cast because the lambda could not throw an exception in which case the `x` would not be of type `Foo`.

For example:

```auto
unless(x is Foo) {
    println("x is not Foo");
}
x.someMethodOnFoo()

```

How ever if you are always going to throw an exception, you could change the signature and the contract to something like:

```auto
inline fun unless(cond: Boolean, fn: () -> Nothing) {
    contract { returns() implies cond }
    if (!cond) fn()
}

```

In that case the smart cast will succeed.

---

<div class="post-metadata">

**Author:** ![Loke](https://avatars.discourse-cdn.com/v4/letter/l/c68b51/32.png) [@Loke](https://discuss.kotlinlang.org/u/Loke)\
**Post date:** [April 14, 2020, 10:42am UTC](https://discuss.kotlinlang.org/t/contract-to-indicate-boolean-state-in-lambda-function/17106/3 "2020-04-14T10:42:33Z")

</div>

Yes. That is clear to me. However, since the function is inlined, I would have expected the Kotlin compiler to be able to figure this out. Arguably it should be able to find that out even without any contracts.
