Home > OS >  How to write sealed class in Kotlin
How to write sealed class in Kotlin

Time:08-06

sealed class DestinationScreen(val route:String){
    object Signup: DestinationScreen(route = "signup")
}

Now I am developing navigation screen above. I don't understand this statement.

object Signup: DestinationScreen(route = "signup")

I think Signup is property. So to set it, should we write this below?

object Signup = DestinationScreen(route = "signup")

Why does not using = issue the instance and set the Signup property?

Please teach me. Thank you.

CodePudding user response:

Nope. Signup is not a property. It's basically a class which extends DestinationScreen except it's a special class object which acts as a singleton and is initiated at the same point it's described. That's why you write it like that.

Why it looks like a property to you is you happen to declare it in another class (which makes it an inner class). But you can declare it outside of the class too.

More about Kotlin objects https://kotlinlang.org/docs/object-declarations.html

CodePudding user response:

Sealed classes represent a class with a fixed number of subclasses. At first, you declare the parent class, for example, a class that describes Screen of your app. Then, you declare all children of this class. For example, HomeScreen and LoginScreen:

sealed class Screen

class HomeScreen : Screen()
class LoginScreen : Screen()

All subclasses can be written outside of the parent class (but must be located in the same file due to compiler limitations).

You can use the object keyword instead of class modifier in case of the class has no properties. It means that the object keyword declares a singleton class.

CodePudding user response:

Because you are using inheritance, not an assigment.

A sealed class is a class which subtypes are known by the compiler so it allows you to create flow controls by type:

sealed class Result {
     data class Success(val data...): Result()
     data class Error(val exception...): Result()
}

So you can do:

when(val result = ...) {
    is Success -> result.data
    is Error -> result.error
}

Whith normal inheritance like on interfaces, open classes or abstract classes you dont know the typed thar inherit from the super type.

  • Related