What's the preferred way to declare an alternative...
# codereview
d
What's the preferred way to declare an alternative result in Kotlin:
Copy code
// 1
data class SomeResult(val typeOne: Bundle? = null, val orTypeTwo: Intent? = null)

if (typeOne == null) 
   doSomething(typeTwo)
else
   doSomething(typeOne!!)
or:
Copy code
// 2
sealed class SomeResult {
    class TypeOneWrapper(val result: Bundle) : SomeResult

    class TypeTwoWrapper(val result: Intent) : SomeResult
}

when (result) {
  is TypeOneWrapper -> doSomething(result)
  is TypeTwoWrapper -> doSomething(result)
}
The second seems cleaner, but requires funny ...Wrapper and val names (since the result type is not owned by me...), but the first is not as robust (doesn't ensure that at least one is set...).
2️⃣ 2
z
Third option is the Kotlin stdlib’s
Result
type: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html
d
It's not a failure or success, it's addAccount in Android's AccountManager (and other such functions -- that return a bundle with special keys, and looks like a big mess in the code...)
I also liked (2), but finding good names is hard 🙃, especially when the property also needs a name...
z
“Failure or success” is just what
Result
happens to represent – you could use the pattern for the union of any types.
d
Interesting point... they use
Any?
as the type and do all the checks inside... which is a bit like (1) usage wise, but hidden in the class...
k
This depends on how you would call it no? Why not just make 2 methods?
d
2 methods? You mean
fun Bundle.asAccountResponse(): Account
and
fun Bundle.asRegistrationIntent():Intent
(which is my real use case).... but then how do you validate what was returned?
k
Sorry, I looked on my phone, and thought the first case was a function signature instead of a dataclass. Looking at it again, I would go with the second case I think.
j
i think
(result as? Type1)?.let{...}?:(result as? Type2)?.let{...}?: ...
is under represented for simple expressions. but
abstract SomeResult.doSomething()
seems like the least astonishing thing a maintainer might read.