0

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)
        }
    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Darotudeen
  • 1,914
  • 4
  • 21
  • 36
  • Oh I just discovered generic classes and I think this will help me understand this – Darotudeen Feb 15 '20 at 19:07
  • A sealed class is like an Enum except each class can hold different values/parameters vs an enum they all need the same params. – Blundell Feb 15 '20 at 19:31
  • This is a design mistake and should probably be replaced with https://github.com/android/architecture-components-samples/blob/6475785613db144578b63eca04b03b89d7bb64a7/GithubBrowserSample/app/src/main/java/com/android/example/github/vo/Resource.kt#L27-L41 – EpicPandaForce Feb 15 '20 at 20:57
  • Can you please provide a link to the codelab you are refering to? – nyxee Mar 26 '21 at 00:27

1 Answers1

0

Result<*>.succeeded is an extension property of the sealed class Result.

Check the guide on extensions in Kotlin:

https://kotlinlang.org/docs/reference/extensions.html

Ahmed AlAskalany
  • 1,600
  • 1
  • 13
  • 13