given `data class Person(val name: String?, val ag...
# announcements
p
given
data class Person(val name: String?, val age: Int?)
is there any way to have
inline val Person.isValid get() = name != null && age != null
allow for smart-casting when accessing `name`/`age`?
t
I'm not sure, bur I think you could do that with the experimental contract API (the same that's used by
checkNotNull
or
requireNotNull
stdlib functions)
r
yup, you can kinda do with the experimental API. This should work:
Copy code
@ExperimentalContracts
fun isValidPerson(name: String?, age: Int?): Boolean {
    contract {
        returns(true) implies (name != null)
        returns(true) implies (age != null)
    }
    return name != null && age != null
}


@OptIn(ExperimentalContracts::class)
fun test() {
    val p = Person("a", 10)
    if (isValidPerson(p.name, p.age)) {
        print(p.name.capitalize())
        print(p.age.toString())
    }
    
}
p
Thanks