https://kotlinlang.org logo
Title
a

andym

04/22/2021, 3:07 PM
I’d like a convenience extension to return true when a nullable string is not null, and not blank — neither should be processed. After the extension returns true for an immutable, I don’t want to have to have to
!!
it. But it seems I can’t use “this” in a contract:
contract {
        returns(true) implies (this != null)
    }

    return !this.isNullOrBlank()
Is there a way to do this?
y

Youssef Shoaib [MOD]

04/22/2021, 3:28 PM
you need to use a qualified this instead, and so assuming your function is called
myCastAsNullOrBlankFun
, then your contract should be this:
contract {
    returns(true) implies (this@myCastASNullOrBlankFun != null)
}
n

Nicolas B

04/22/2021, 3:32 PM
Why you use a contrat ?
fun String.checkNotNull(): Boolean{
    return !isNullOrBlank()
}
e

ephemient

04/22/2021, 4:06 PM
fun String.isNullOrBlank()
itself has a contract,
contract {
    returns(false) implies (this@isNullOrBlank != null)
}
not clear why you would need another function to wrap it, but for sure the
this
you wrote is not referring to what you think it is - it's
this@contract
a

andym

04/22/2021, 4:50 PM
@Youssef Shoaib [MOD] perfect, thanks!
@Nicolas B, I would prefer a contract so that after I prove my immutable value is not null, I don’t need
!!
, or anything else — I just want a custom smart-cast to non-nullable