I am learning generics and I have written such a class, but I am not quite sure how it works.
This is the code:
sealed class Result<out T> {
abstract val data: T?
abstract val error: String?
class Success<out T>(override val data: T) : Result<T>() {
override val error: String? = null
}
class Error<out T>(override val error: String, override val data: T? = null) : Result<T>()
}
fun main() {
val resultNullable = getResultNullable()
println(resultNullable.data)
}
fun getResultNullable(): Result<String?> {
return Result.Success(null)
}
This code works fine, but i wonder why this line doesn’t throw any error:
return Result.Success(null)
The class Success is declared to accept non-nullable value of type T, but it indeed accepts null. Shouldn’t it be declared as below to accept null values?:
class Success<out T>(override val data: T?) : Result<T>() {
override val error: String? = null
}
I was searching for explanation on the web, but I am struggling with understanding, so I decided to bring my own example here. Thank you in advance for any support.