简体   繁体   English

为什么我不需要在 Kotlin 密封的 class 中写入属性 object class?

[英]Why don't I need to write property at object class in sealed class by Kotlin?

I'm developing the app by using Kotlin.我正在使用 Kotlin 开发应用程序。

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

@Composable
fun InstagramApp(){
 
    val navController = rememberNavController()
    
    NavHost(navController = navController, startDestination = DestinationScreen.Signup.route){
        composable(DestinationScreen.Signup.route){
            SignupScreen(navController = navController)
        }
    }
}

I don't know Why Signup singleton class can have the property "route" using argv?我不知道为什么 Signup singleton class 可以使用 argv 拥有属性“route”? I understand it inherits DestinationScreen.我了解它继承了 DestinationScreen。 So it also has route property.所以它也有路由属性。

But Destination class doesn't have concrete the property route .但是 Destination class 没有具体的属性route If Destination class is data class, make sense it doesn't need to declare the property.如果 Destination class 是数据 class,则不需要声明该属性。 No need for {} .不需要{} And data class has the property not declareing it by using argv.数据 class 具有未使用 argv 声明的属性。 So I mean DestinationScreen should has concrete property route , if Signup inherit different property's value, it should override.所以我的意思是 DestinationScreen 应该有具体的属性route ,如果 Signup 继承不同属性的值,它应该覆盖。 Why can this codes above work?为什么上面的代码可以工作? Does this feature have seal class or object class?此功能是否有密封 class 或 object class?

Please teach me.请教我。 Thank you.谢谢你。

But Destination class doesn't have concrete the property route但是 Destination class 没有具体的属性route

Yes, it does.是的,它确实。 The route property is declared right there in its constructor. route属性在其构造函数中就在那里声明。

if Signup inherit different property's value, it should override如果 Signup 继承了不同属性的值,它应该覆盖

Not sure what you mean by this, but Signup doesn't need to override the property.不确定您的意思,但 Signup 不需要覆盖该属性。 It already inherits the property.它已经继承了财产。 By passing a value to the super-class's constructor, the existing property gets an initial value as passed by the sub-class without overriding it.通过将值传递给超类的构造函数,现有属性将获得子类传递的初始值,而无需覆盖它。

You mention sealed and data class types, but they are irrelevant to this discussion.您提到了sealeddata class 类型,但它们与本次讨论无关。 Inheritance works the same way with sealed and non-sealed classes. Inheritance 对密封类和非密封类的工作方式相同。

Any time a class extends another class, it also is a type of that class and inherits all of its properties and functions, no overriding needed.任何时候 class 扩展另一个 class,它也是 class一个类型,并继承它的所有属性和功能,不需要覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM