are there plans to leverage contracts? i find i d...
# kotlintest
b
are there plans to leverage contracts? i find i do something like this here and there:
Copy code
val result = func(): String?
result shouldNotBe null
result as String
result.startsWith("...") shouldBe true
it'd be nice to have a contract for
shouldNotBe null
so wouldn't have to explicitly cast
well, maybe this is a dumb use case, i could just use
?.
there, but, given i've asserted it's already not null it'd be a nice-to-have
s
I thought we'd added that already
@LeoColman ?
l
We added for shouldBeInstanceOf
I think contracts are not smart enough for shouldNotBe null yet
Cause we'd have to say "if paramaeter is null and this returns, it wont be null"
And this is impossible afaik
@bbaldino use
shouldBeInstanceOf
s
Isn't should not be null the same as if (a ! =null) { } ?
l
Yes, but you can also use
foo shouldNotBe bar
b
i was just playing with this:
Copy code
@ExperimentalContracts
fun foo(x: Any?) {
    contract {
        returns() implies (x != null)
    }
    if (x == null) {
        throw Exception()
    }
}
l
And i cant create a contract for both cases
b
which works with
Copy code
val x: String? = null

        foo(x)
        x.startsWith("asdsd")
but maybe that's not a good approximation of the flow in
shouldNotBe
i just kinda took a quick look at it
l
Let me get to my pc and I'll explain some cases that wouldnt work
Hm... Perhaps it's not actually a problem for the shouldNotBe case?
I was fearing that people would not be able to use
a shouldNotBe b
if b was null
But
a shouldNotBe b
will always fail if b is null and a is null, so that's ok
And if a is not null, then it will never fail
Yeah, perhaps that works
👍🏻 1
Thinking again...
With the code
Copy code
val a: String? = "foo" // A is not guaranteed to not be null

a shouldNotBe "Bar"

a.length shouldBe 125
This will fail, because the contract will say that "If shouldNotBe returns,
a
is not null"
What we can do is
a.shouldNotBeNull()
And we already have that feature
Copy code
fun Any?.shouldNotBeNull() {
  contract {
    returns() implies (this@shouldNotBeNull != null)
  }

  this shouldNot beNull()
}
And it already has the contract, so idk
I closed the issue. I don't think this is possible with the current contracts.
b
oh, i don't see
shouldNotBeNull
, is it in a recent update?
but that's good to know, thanks
l
Perhaps it wasn't published yet? I'm not sure
Which version are you using? I'm pretty sure it's in the latest version
b
3.3.0
oh, nm
my other project (where i check before) is on an older one
i do see it in 3.3.0