Home > Enterprise >  Why need the author to add override before val in a data class in order to instance an interface in
Why need the author to add override before val in a data class in order to instance an interface in

Time:10-19

The Code A is from the official sample project.

I find override is added before val route in data class TopLevelDestination, but it's hard to understand to instance the interface NiaNavigationDestination in this way.

Is there other way to instance the interface NiaNavigationDestination ?

Code A

data class TopLevelDestination(
    override val route: String,
    override val destination: String,
    val selectedIcon: Icon,
    val unselectedIcon: Icon,
    val iconTextId: Int
) : NiaNavigationDestination


interface NiaNavigationDestination {
    val route: String
    val destination: String
}

CodePudding user response:

You can override the vals from the interface in the body of the class, but then they will not participate in equals(), hashcode(), or copy(). A data class only uses its constructor parameters for those functions.

Example:

data class TopLevelDestination(
    val selectedIcon: Icon,
    val unselectedIcon: Icon,
    val iconTextId: Int
) : NiaNavigationDestination {
    override val route: String = "something"
    override val destination: String = "something else"
}

In this case, it does not seem productive for something like "destination" to not be a part of equals() for a class that has "destination" in it's name!

It also becomes impossible to set these values to anything but a constant or something that depends on the other constructor properties.

  • Related