I've come across the use of a sealed class in the ...
# announcements
m
I've come across the use of a sealed class in the Jetpack Compose Jetnews example code that I think has general applicability. I'm new to Kotlin and don't understand this construction of a generic class with 2 type parameters. I'd appreciate pointers to docs or articles that explain it. Thanks!
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
👌 1
2
d
At first, I'm assume that the
Result<out R>
is a typo and it should be
Result<out T>
? A good explanation of this construct and possible usage scenarios could be found in this article. In my own simple words: Most prominent example might be the typical network response where you either have a success with a payload or an error with a reason. It avoids this (anti) pattern to have response classes with
isSuccess
boolean and a payload and error property and one of both is set depending on the success status.
m
Nope, Result<out R> is not a typo. This code snippet is lifted from the functioning Jetnews Compose example.
d
There is no class with two type parameters here.
Result
has one type parameter called
R
.
Success
has one type parameter called
T
.
Success
then extends
Result
and sets `Result`'s type parameter to whatever its own
T
is. So a
Success<String>
is a
Result<String>
.
Error
is special, it has no type parameters, and instead every
Error
is a
Result<Nothing>
.
👍 4
1
m
Thanks, for the explanation, Take! Your explanation makes things clear for me.
a
Nothing
is top-most type in the type system (subclass of every class) sort of imaginary, and hence no object can satisfy it. For example:
Copy code
var a = if(cond) 10 else 10.5
a = "Hello"  // error: a must be a Number
the type of a is inferred as
Number
, as Int and Double are subclasses of Number. Similarly, if you do something like this:
Copy code
var b = null
the inferred type would be closest intersection, in this case is
Nothing?
, a nullable Nothing, and hence you cannot assign anything to b. This is not really a good example where it is used, but you can instead find better examples in 'contravariance' sections with
in
modifiers, to understand better.