Understanding the Nuances: Result<Any> vs. Result<*>

Vishal
2 min readMar 2, 2024
Photo by Florian Olivo on Unsplash

Both Result<Any> and Result<*> are ways to represent the outcome of an operation in Kotlin, but they differ in their flexibility and type safety:

1. Result<Any>:

  • Behavior:
  • Represents the result of an operation that can return any type of value.
  • It’s a generic class with a single parameter T representing the type of the successful result.
  • When used as Result<Any>, however, T is inferred to be Any, allowing any possible type for the value.

2. Result<*>:

  • Behavior:
  • Represents the result of an operation that can also return any type of value.
  • It utilizes the star projection (*) to indicate that the type parameter T is unknown and cannot be determined at compile time.
  • Similar to Result<Any>, it allows any potential type for the value.

Similarities:

  • Both Result<Any> and Result<*> handle success and error scenarios using a sealed class with two subclasses:
  • Success(value: T): Represents a successful operation with a value of type T.
  • Error(exception: Throwable): Represents an error that occurred during the operation.

Differences:

  • Type safety:
  • Due to type inference, Result<Any> offers less type safety because the compiler doesn't know the specific type of the successful value. This could lead to runtime type checks or potential casting issues.
  • Conversely, Result<*> provides no explicit type information at compile time, offering even less type safety than Result<Any>. This requires additional care and potential runtime checks when accessing the value.

When to use which:

  • Prefer Result<T> where the successful result type is known and specific. This provides better type safety and avoids unnecessary runtime checks.
  • Use Result<Any> cautiously when the successful result type can be any possible type, but be aware of potential runtime type checks.
  • Avoid Result<*> in general due to its lack of type information and potential safety concerns. Consider using Result<Any> instead if you need to handle any possible type, but understand the trade-off in type safety.

Remember: When choosing between Result<Any> and Result<*>, prioritize better type safety and clarity. If you need to handle a wider range of potential types but still want some level of type information, consider using Result<Any> with caution and appropriate type checks.

Happy Coding…….

--

--

Vishal

Senior Android Dev | Blog Writer @Stackademic @NerdForTech