I have been doing android development for a while but I always looking forward to learning new things.
I came across the code below on codelab for viewmodel unit testing. I really like the code base is arranged but do not understand some codes like the one below.
I will like some guidance on creating a class that has a type of map as below.
Basically I will like to know how Result<*> still relate to Result and why the class is just called/implemented as Success(it).
I will appreciate a kind guidance.
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object Loading : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
Loading -> "Loading"
}
}
}
/**
* `true` if [Result] is of type [Success] & holds non-null [Success.data].
*/
val Result<*>.succeeded
get() = this is Success && data != null
//implementation
override fun observeTask(taskId: String): LiveData<Result<Task>> {
return tasksDao.observeTaskById(taskId).map {
Success(it)
}
}
Result<*>.succeeded
is an extension property of the sealed class Result
.
Check the guide on extensions in Kotlin: