I just watched the presentation on the new Rich Er...
# language-proposals
d
I just watched the presentation on the new Rich Errors language feature. Since
?
and
!!
will be used as well for error types, how are we going to differentiate between null and error in a function returning a nullable type?
Copy code
fun foo() String? | SomeError
I was surprised this wasn’t addressed at all in the talk. Are we supposed to either write functions with error union types OR functions returning nullable without error union types? What about generics versions of this? A
null
can be a valid successful response
m
In our type system,
String?
can be viewed as
String | Null
, which has a shorthand syntax. The generalized rules of
?.
and
!!
apply here as well:
Copy code
foo()?.length // type is Int | Null | SomeError ~ Int? | SomeError
foo()!! // string -> NOP, null -> NPE, SomeError -> KotlinException
So the behavior is the same as if the return type was just `String?`: a safe call results in
Int?
, and
!!
throws an NPE if the value is
null
. In the presence of errors, we extend this behavior.
A
null
can be a valid successful response
That’s correct, this doesn't change. However, if you want to explicitly signal that a value might be missing, it’s better to consider returning something like
String | NotFound | SomeError
👍 1
1
👍🏾 1
💯 1
d
Thank you @mikhail.zarechenskiy for the answer. You are saying that we should modify how we code to use some error conditions over null, can we expect existing APIs to do the same? Such as collection.first() returning a NoSuchElement and firstOrNull() getting deprecated? What will happen to the current APIs with this change? Will contracts get some love as well and include support for these new errors?
m
can we expect existing APIs to do the same?
Such as collection.first() returning a NoSuchElement and firstOrNull() getting deprecated?
What will happen to the current APIs with this change?
Most likely, the existing API will stay the same. Especially functions like
first
that are everywhere. We don't plan to have any massive migration with the introduction of this feature. Speaking of contracts — we'll see, but what is your use-case regarding contracts?
d
I find contracts very useful but very limited at the moment. And they are still marked experimental. I cannot think of a specific use case on the spot, I know I’ve encountered situations where I wish I could express a contract but it wasn’t supported, cannot remember any specific one at the moment. I’ll write here next time. My impression as a developer is that contracts were released as experimental and then abandoned, if the current API is considered stable and you do not plan to add more feature I would at least expect it to NOT be experimental.
446 Views