trying to wrap my head around Contracts. ```class...
# announcements
b
trying to wrap my head around Contracts.
Copy code
class Person(val email: String?)
inline class Email(val value: String) 

fun Person.email() {
  return this.email?.let {
    Email(email)
  } 
}
basically an extension method on a class that will null-check a value and return it wrapped in an inline class. how do i tell the compiler that if the function
Person.email()
returns non-null then the
instance.email
property is also not null. is that possible? am i fundamentally misunderstanding contracts?
l
I think this is possible
But I don't know how
r
Setting aside whether that is possible, how would that be in any way useful?
1
b
it’s admittedly a contrived example
instance.email()
then at some point later for some reason i need to access the raw value as
instance.email
and that returns a String? when i know due to checking
instance.email()
that it’s not null
basically the ability to say: if some computed property of
instance
is not null, it implies that property
y
of
instance
is also not null
k
The contracts don't allow you to express this yet
d
There's very little point in having a class be inline when you make it nullable. It can very much work against you when you box and unbox it over and over. If you want to use inline classes, make sure you understand when they can give you a performance benefit and always view the byte code in intellij to check your assumptions.
For example, last time I checked, comparing inline classes other than unsigned integer variants using == generated instructions to box both operands to perform the comparison with a virtual call (all jvm)
They may have fixed this by now, bottom like is they're experimental, use accordingly
b
i don’t care about the performance in this case, i only care about the type safety
d
I think the only use case for inline classes is performance. If you don't care about it, drop the inline modifier.
b
well, that’s very fair 🙂 though, i think the expressivity of the contract would be exactly the same in this case whether the class is inline or not