Skip to content

Add UnsafeResultValueAccess annotation to Result class for safer value access #123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions buildSrc/src/main/kotlin/kotlin-conventions.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ kotlin {
all {
languageSettings.apply {
optIn("kotlin.contracts.ExperimentalContracts")
optIn("com.github.michaelbull.result.UnsafeResultValueAccess")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,12 @@ public value class Result<out V, out E> internal constructor(
private val inlineValue: Any?,
) {

@UnsafeResultValueAccess
@Suppress("UNCHECKED_CAST")
public val value: V
get() = inlineValue as V

@UnsafeResultValueAccess
@Suppress("UNCHECKED_CAST")
public val error: E
get() = (inlineValue as Failure<E>).error
Expand Down Expand Up @@ -102,3 +104,19 @@ private class Failure<out E>(
return "Failure($error)"
}
}

/**
* Marks access to [Result.value] or [Result.error] as potentially unsafe unless the [Result]
* is explicitly checked for [Result.isOk] or [Result.isErr] beforehand.
*
* Ensure that you verify the [Result] state using [Result.isOk] or [Result.isErr] before accessing its value.
* Alternatively, consider using the [Result.fold] function to safely handle the result.
*/
@RequiresOptIn(
level = RequiresOptIn.Level.ERROR,
message = "Accessing Result.value or Result.error without checking the Result state may lead to unsafe behavior.",
)
@MustBeDocumented
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.PROPERTY)
public annotation class UnsafeResultValueAccess