Home > Software engineering >  Why is there a object class defined within sealed class when I use Kotlin?
Why is there a object class defined within sealed class when I use Kotlin?

Time:03-25

The Code A is from the official sample project.

Result<out R> is a sealed class, I'm very strange why Loading is defined as object class.

I think the Code B is more reasonable, is it right?

Code A

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"
      }
   }
}

Code B

sealed class Result<out R> {
   data class Success<out T>(val data: T) : Result<T>()
   data class Error(val exception: Exception) : Result<Nothing>()
   data class Loading : Result<Nothing>()

   override fun toString(): String {
      return when (this) {
         is Success<*> -> "Success[data=$data]"
         is Error -> "Error[exception=$exception]"
         is Loading -> "Loading"
      }
   }
}

CodePudding user response:

that won't work, because:

data class Loading : Result<Nothing>() <-- this isn't valid for a data class

Data classes must have at least one primary constructor parameter, presumably the author used an object there to avoid having to make use of a constructor value, compared to the others:

 data class Success<out T>(val data: T) : Result<T>() <-- (val data: T)
 data class Error(val exception: Exception) : Result<Nothing>() <-- (val exception: Exception)

which clearly require values

CodePudding user response:

There's no reason not to use an object for a class that doesn't have any properties (holds no state). object means you don't have to create multiple instances of it and you never have to worry about which instance you're looking at, so it's simpler. You don't have to call a constructor on it to get an instance, and there will never be more than one instance of it taking up memory.

Note that your is Loading check in Code B will still work if Loading is an object. objects are more versatile because == and is checks are both valid and effectively mean the same thing.

By the way (as mentioned before by @a_local_nobody), you cannot create a data class with no properties, although you could create a regular class.

  • Related