https://kotlinlang.org logo
b

bod

05/11/2020, 8:49 AM
Hello, World! Hey I was looking at contracts again (even though they're still experimental), and couldn't find a way to do what I want, so I'm wondering if it's possible. I have a
fun parseDate(dateStr: String?): Date?
and want to express that if
dateStr
is
null
then the result will be
null
- and also the opposite. Possible?
r

rafi

05/11/2020, 9:18 AM
When you say "the opposite", does it mean that "if dateStr is not null then the result will not be null" ? If yes it seems risky since dateStr could be malformed
b

bod

05/11/2020, 9:23 AM
Yes that's what I mean. Let's ignore the malformed case for now (I think this will be handled by throwing, not by returning
null
)
r

rafi

05/11/2020, 11:55 AM
Something like returnsNotNull() implies dateStr != Null maybe ?
b

bod

05/11/2020, 12:10 PM
I've tried, but it's still red if I do something like
val d: Date = parseDate(nonNullStr)
(red because
parseDate
can return null according to the compiler, even though it's not possible in that case)
d

dmitriy.novozhilov

05/12/2020, 10:04 AM
Contracts works in opposite way. Contract
returnsNotNull() implies dateStr != Null
means that "if call
parseDate(str)
returned not null than `str != null`" There is no support of contracts that you want but we are considering support this case
b

bod

05/12/2020, 10:07 AM
Thanks a lot for chiming in. It may be just me but I have the impression that this use-case would be one of the most common ones.