You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I noticed that the new inline value class in API 2.0 lets us access result.value directly without checking if it’s actually safe, which wasn’t the case before. Here’s what I mean:
val result:Result<Int, SomeError> = getResult()
result.value // This compiles even if the result is an error, leading to potential runtime errors.
This could lead to runtime exceptions that were harder to make before when the API required type checking and more explicit unwrapping using getOrThrow() (which is a lot easier to catch or denylist through code analysis).
It seems like API 2.0 introduces a downgrade in compile-time safety compared to the previous version. Could we consider reinstating some form of this safety, perhaps through Kotlin contracts or another mechanism, to prevent potential runtime errors?
The text was updated successfully, but these errors were encountered:
kirillzh
changed the title
Result 2.0: unsafe unwrapping via Result.value
Result 2.0: unsafe unwrapping of Result.value and Result.errorJun 3, 2024
Could we consider reinstating some form of this safety, perhaps through Kotlin contracts or another mechanism, to prevent potential runtime errors?
Do you have a proposal of which compiler contract would achieve this? We effectively need user-defined guards, such that you can't call .value unless you've done an isOk/isErr check - I don't think such a thing exists in Kotlin?
If value is always available, then maybe it should be nullable. This way we can check if it is null, and get smart cast.
It would also mean that people are more likely to use better approaches such as doing .onSuccess { value -> } given that inside the lambda, "value" wouldn't be null.
It being nullable would force it to be boxed at all call sites. See the following example from Kotlin's docs:
interfaceI
@JvmInline
value classFoo(vali:Int) : I
funasNullable(i:Foo?) {}
funmain() {
val f =Foo(42)
asNullable(f) // boxed: used as Foo?, which is different from Foo
}
I noticed that the new inline value class in API 2.0 lets us access result.value directly without checking if it’s actually safe, which wasn’t the case before. Here’s what I mean:
This could lead to runtime exceptions that were harder to make before when the API required type checking and more explicit unwrapping using
getOrThrow()
(which is a lot easier to catch or denylist through code analysis).It seems like API 2.0 introduces a downgrade in compile-time safety compared to the previous version. Could we consider reinstating some form of this safety, perhaps through Kotlin contracts or another mechanism, to prevent potential runtime errors?
The text was updated successfully, but these errors were encountered: